86. 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的节点之前。
应该保留两个分区中每个分区中节点的原始相对顺序。
具体的思路
建立两个链表,一个放比X值大的节点,一个放比X值小的节点。最后把两个链表拼接在一起。
代码实现如下
public static ListNode partition(ListNode head, int x) {
if(head == null || head.next == null)
return head;
ListNode p = head;
ListNode fir = new ListNode(0);
ListNode sec = new ListNode(1);
ListNode rf = fir;
ListNode rc = sec;
int i = 0 ;
while(p != null) {
ListNode temp = p.next;
if(p.val < x) {
//后插法抽取节点形成新的链表
rf.next = p;
p.next = null;
rf = p;
}
else {
rc.next = p;
p.next = null;
rc = p;
}
p = temp;
}
rf.next = sec.next;
return fir.next;
}
思考
在做这个题的过程中,有一个产生了一个问题:
一个链表如果没有头结点,怎么遍历删除?:
在链表中删除一个节点, 一般情况下要知道当前要删除节点p的前一个节点 pre 。如果没有头结点的话,我们很难遍历删除这样的节点。
所以,想到一个新的方法来删除当前节点p
我们把p节点的下一个节点的属性赋值给p,然后让p指针指向下一个节点的下一个节点,通过这种方式我们就“变相”的删除了p节点
p = p.next.value;
p = p.next.next;
- 以后希望能有一个机会,把遇到的问题总结一下,出一个汇总贴吧。