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的值,小于x都放在大于等于x的前面,并且不改变链表之间node原始的相对位置。每次看这道题我老是绕晕,纠结为什么4在3的前面。。其实还是得理解题意,4->3->5都是大于等3的数,而且这保持了他们原来的相对位置 。

所以,这道题是不需要任何排序操作的,题解方法很巧妙。

new两个新链表,一个用来创建所有大于等于x的链表,一个用来创建所有小于x的链表。

遍历整个链表时,当当前node的val小于x时,接在小链表上,反之,接在大链表上。这样就保证了相对顺序没有改变,而仅仅对链表做了与x的比较判断。

最后,把小链表接在大链表上,别忘了把大链表的结尾赋成null。

 代码:

 1 public class PartitionList {
 2 
 3     public static void main(String[] args) {
 4         // TODO Auto-generated method stub
 5         ListNode head = new ListNode(1);
 6         // head.add(1);
 7         head.add(4);
 8         head.add(3);
 9         head.add(2);
10         head.add(5);
11         head.add(2);
12         head.print();
13         System.out.println();
14         partitionList(head, 3).print();
15     }
16 
17     public static ListNode partitionList(ListNode head, int x) {
18         if (head == null || head.next == null)
19             return head;
20         ListNode small = new ListNode(-1);
21         ListNode newsmallhead = small;
22         ListNode big = new ListNode(-1);
23         ListNode newbighead = big;
24         while (head != null) {
25             if (head.data < x) {
26                 small.next = head;
27                 small = small.next;
28             } else {
29                 big.next = head;
30                 big = big.next;
31             }
32             head = head.next;
33         }
34         big.next = null;
35         small.next = newbighead.next;
36         return newsmallhead.next;
37     }
38 }
原文地址:https://www.cnblogs.com/ncznx/p/9321053.html