zoukankan      html  css  js  c++  java
  • Partition List ——LeetCode

    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值大的元素,记录其前驱节点ptr,然后遍历单链表,大于x的跳过,小于x的接到ptr的后面,然后ptr=ptr.next。

       public ListNode partition(ListNode head, int x) {
            if (head==null||head.next == null) {
                return head;
            }
            ListNode dummy = new ListNode(0);
            dummy.next = head;
            ListNode ptr = dummy;
            ListNode pre = dummy;
            while(ptr!=null&&ptr.next!=null&&ptr.next.val<x){
                ptr=ptr.next;
                pre=pre.next;
            }
            while(pre.next!=null){
                ListNode tmp = pre.next;
                if(pre.next.val<x){
                    ListNode curr = pre.next;
                    pre.next=curr.next;
                    curr.next=ptr.next;
                    ptr.next=curr;
                    ptr=ptr.next;
                }
                pre = tmp;
            }
            return dummy.next;
        }
  • 相关阅读:
    第三周课程总结
    Java第一次学习总结
    第十二周编程总结
    第九周作业
    第八周作业
    第五周编程总结
    第三周作业
    第二周编程总结
    JAVA第二周学习总结
    2019春总结作业
  • 原文地址:https://www.cnblogs.com/aboutblank/p/4528347.html
Copyright © 2011-2022 走看看