Leetcode -- 86. Partition List (以及关于没有头结点链表遍历修改的问题)

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;
  • 以后希望能有一个机会,把遇到的问题总结一下,出一个汇总贴吧。
2017-3-18 design by zx
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值