LeeCode partition List

来源:互联网 发布:网络转盘游戏 编辑:程序博客网 时间:2024/05/16 18:09

 

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.

class Node{private int val; Node next;public Node(int val) {this.val = val;this.next = null;}}
public Node partition(Node head, int x) {Node fakeNode1 = new Node(0);fakeNode1.next = head;Node fakeNode2 = new Node(0);Node p = fakeNode1;Node n = fakeNode2;    while(p.next!=null){if(p.next.val<x){Node after = p.next.next ; Node cur = p.next;p.next  =  after;n.next = cur;n = n.next;}else{p = p.next;}}  n.next = fakeNode1.next;return fakeNode2.next;}


先创建2个头指针分别指向大于x的Node节点组成的List 和小于x的Node节点组成的List的头节点

遍历时,如果遇到大于x值的直接往后移一位,如果遇到小于x值的那么就把那个小于x值的节点取出来

放入另一个List中。 p 和n 分别用来跟踪两个List的Node。结束后将他们接起来。时间复杂O(n)。

 

0 0
原创粉丝点击