LeetCode086——分隔链表

版权声明:版权所有,转载请注明原网址链接。 https://blog.csdn.net/qq_41231926/article/details/83021650

我的LeetCode代码仓:https://github.com/617076674/LeetCode

原题链接:https://leetcode-cn.com/problems/partition-list/description/

题目描述:

知识点:链表

思路:新建两个链表,其中一个存储小于x的节点,另一个存储大于或等于x的节点

原本的第一思路是用双指针来遍历原链表,一个指针指向小于x节点的最后一个节点,而另一个指针则负责遍历链表,当寻找到某个小于x的节点,则交换位置。但是发现很难处理head = 1 -> 1, x = 3这样的情形。不如直接新建两个链表来得思路清晰。

时间复杂度和空间复杂度均是O(n),其中n为head链表中的节点数。

JAVA代码:

public class Solution {

    public ListNode partition(ListNode head, int x) {
        if(null == head || null == head.next){
            return head;
        }
        ListNode lessNode = new ListNode(-1);
        ListNode greaterNode = new ListNode(-1);
        ListNode cur = head;
        ListNode cur1 = lessNode;
        ListNode cur2 = greaterNode;
        while(null != cur){
            ListNode temp = new ListNode(cur.val);
            if(cur.val < x){
                cur1.next = temp;
                cur1 = cur1.next;
            }else{
                cur2.next = temp;
                cur2 = cur2.next;
            }
            cur = cur.next;
        }
        cur1.next = greaterNode.next;
        return lessNode.next;
    }
}

LeetCode解题报告:

扫描二维码关注公众号,回复: 3639487 查看本文章

猜你喜欢

转载自blog.csdn.net/qq_41231926/article/details/83021650