Partition List

来源:互联网 发布:淘宝足迹不是本人浏览 编辑:程序博客网 时间:2024/06/07 22:52

Given a linked list and a value x, partition it such that all nodes less thanx come before nodes greater than or equal tox.

You should preserve the original relative order of the nodes in each of the two partitions.

For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.

思路:用四个标签,跟踪前面list,和后面的list。

这样子就是order顺序的。

如果不考虑顺序的话,可以更简单,直接用两个指针即可。

注意: node.next = null;   这个很关键,取出next节点,就应该把node.next 设置成null; 代表把这个点单独拿出来。不然,最后一个指针,两个list同时指向前面,会串联成一个环,然后会形成死循环,memory会out。

/**  * Definition for singly-linked list.  * public class ListNode {  *     int val;  *     ListNode next;  *     ListNode(int x) { val = x; }  * }  */ public class Solution {     public ListNode partition(ListNode head, int x) {         if(head == null || head.next == null) return head;         ListNode dump1 = new ListNode(0);         ListNode cur1 = dump1;         ListNode dump2 = new ListNode(0);         ListNode cur2 = dump2;         ListNode node = head;         while(node!=null) {             ListNode next = node.next;             node.next = null;             if(node.val <x) {                 cur1.next = node;                 cur1 = node;             } else { // cur.val >=x;                 cur2.next = node;                 cur2 = node;             }             node = next;         }         cur1.next = dump2.next;         return dump1.next;     } }


0 0