码迷,mamicode.com
首页 > 其他好文 > 详细

Partition List

时间:2015-03-29 23:33:04      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:

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     }

 

Partition List

标签:

原文地址:http://www.cnblogs.com/ivanyangzhi/p/4376534.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!