美文网首页LeetCode刷题笔记JAVA语言
86. Partition List(按x分割链表)

86. Partition List(按x分割链表)

作者: cixing | 来源:发表于2018-04-21 15:18 被阅读0次

    自己的方法一

    遍历链表两次

    遍历链表两次
    class Solution {
        public ListNode partition(ListNode head, int x) {
            if(head==null||head.next==null)
                return head;
            int len=0;
            ListNode p=head;
            while(p!=null){
                len++;
                p=p.next;
            }
            ListNode p1=head;
            ListNode p2=head;
            ListNode p3=head;
            ListNode out=new ListNode(0);
            ListNode out1=out;
            while(p2!=null){
                if(p2.val<x){
                    ListNode tmp=new ListNode(p2.val);
                    out.next=tmp;
                    p2=p2.next;
                    out=out.next;
                }
                else
                    p2=p2.next;
            }
            while(p3!=null){
                if(p3.val>=x){
                    ListNode tmp=new ListNode(p3.val);
                    out.next=tmp;
                    p3=p3.next;
                    out=out.next;
                }
                else
                   p3=p3.next;
            }
            return out1.next;
    }}
    

    自己的方法二

    遍历一次

    class Solution {
        public ListNode partition(ListNode head, int x) {
            if(head==null||head.next==null)
                return head;
            ListNode out = new ListNode(0);
            ListNode pre = out;
            ListNode out1 = out;
            while(head!=null){
                if(head.val<x){
                    ListNode tmp = new ListNode(head.val);
                    out.next = tmp;
                    head = head.next;
                    out = out.next;  
                    pre = out;
                }
                else
                    break;
            }
            while(head!=null){
                if(head.val>=x){
                    ListNode tmp = new ListNode(head.val);
                    out.next = tmp;
                    head = head.next;
                    out = out.next;
                }
                else{
                    ListNode tmp = new ListNode(head.val);
                    ListNode tmp1=pre.next;
                    pre.next = tmp;
                    tmp.next = tmp1;
                    head = head.next;
                    pre = pre.next;
                }
            }
            return out1.next;      
    }}
    

    相关文章

      网友评论

        本文标题:86. Partition List(按x分割链表)

        本文链接:https://www.haomeiwen.com/subject/ttexlftx.html