Partition List

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

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.

思路一:

遍历原链表,将比x小的元素拿出来依次插入新的链表,最后将原链表剩下的节点插在新链表后面即得到结果。

 1 public ListNode partition(ListNode head, int x) {
 2         //dummy节点用来记录原列表的头
 3         ListNode dummy = new ListNode(0);
 4         dummy.next = head;
 5         ListNode pre = dummy;
 6         //ret依次存储比x小的节点
 7         ListNode ret = new ListNode(0);
 8         //tail节点用来记录ret链表的尾部
 9         ListNode tail = ret;
10         //遍历原链表
11         while (head != null) {
12             //当前节点值比x小时,插入在tail节点后
13             if (head.val < x) {
14                 tail.next = head;
15                 tail = tail.next;
16                 pre.next = head.next;
17             } else {
18                 pre = pre.next;
19             }
20             head = head.next;
21         }
22         //将原链表剩下的节点直接加在tail节点后面
23         tail.next = dummy.next;
24         return ret.next;
25     }

 

posted on 2015-03-29 22:11  绿树荫  阅读(101)  评论(0编辑  收藏  举报

导航