资讯专栏INFORMATION COLUMN

[LintCode/LeetCode] Partition List

崔晓明 / 3371人阅读

摘要:新建两个链表,分别存和的结点。令头结点分别叫作和,对应的指针分别叫作和。然后遍历,当小于的时候放入,否则放入。最后,让较小值链表尾结点指向较大值链表头结点,再让较大值链表尾结点指向。

Problem

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.

Example

Given 1->4->3->2->5->2->null and x = 3,
return 1->2->2->4->3->5->null.

Note

新建两个链表,分别存>=x的结点。令头结点分别叫作dummyleftdummyright,对应的指针分别叫作leftright。然后遍历head,当head.val小于x的时候放入left.next,否则放入right.next。最后,让较小值链表尾结点left指向较大值链表头结点dummyright.next,再让较大值链表尾结点right指向null。这样两个新链表就相连了,返回头结点dummyleft.next即可。

Solution
public class Solution {
    public ListNode partition(ListNode head, int x) {
        ListNode dummyleft = new ListNode(0);
        ListNode dummyright = new ListNode(0);
        ListNode left = dummyleft, right = dummyright;
        while (head != null) {
            if (head.val < x) {
                left.next = head;
                left = left.next;
            }
            else {
                right.next = head;
                right = right.next;
            }
            head = head.next;
        }
        left.next = dummyright.next;
        right.next = null;
        return dummyleft.next;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/66204.html

相关文章

  • [LintCode/LeetCode] Meeting Rooms

    Problem Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), determine if a person could attend all meetings. Example Given intervals = [[0,30],[...

    Noodles 评论0 收藏0
  • [LintCode/LeetCode] Nth to Last Node in List

    摘要:依然是一道找倒数第个结点的链表题,用双指针做。先走,然后和一起走,直到为,的位置就是倒数第个位置。 Problem Find the nth to last element of a singly linked list. The minimum number of nodes in list is n. Example Given a List 3->2->1->5->null ...

    Salamander 评论0 收藏0
  • [LintCode/LeetCode] Copy List with Random Pointer

    摘要:大体意思就是,先复制到,顺便将所有的放在再复制所有的到,顺便将所有的放在最后令,令,将和分离,返回的头结点 Problem A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. ...

    Jacendfeng 评论0 收藏0
  • [LintCode/LeetCode] Rotate List

    摘要:而后吾当依除取余之法,化大为小,则指针不致于越界也。后欲寻右起第结点,令快指针先行数日,及至两指针相距为,便吟鞭东指,与慢指针策马共进。快慢指针亦止于其所焉。舞动长剑,中宫直入,直取首级,而一掌劈空,已鸿飞冥冥。自此,一代天骄,霸业已成。 Problem Given a list, rotate the list to the right by k places, where k is...

    Blackjun 评论0 收藏0
  • [LintCode/LeetCode] Convert Sorted List to Balance

    摘要:当链表为空时,中出现大于,返回。然后计算中点,以为界分别递归构建左右子树。顺序是,左子树根结点右子树。由于根节点是直接取构建,当前的已经被取用。所以在下一次递归构建右子树之前,要让指向。最后将和左右子树相连,返回。 Problem Given a singly linked list where elements are sorted in ascending order, conve...

    Michael_Ding 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<