86. 分隔链表

题目链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

86. 分隔链表_第1张图片 题目大意:读了几遍才看懂什么意思,

解题思路:

AC代码:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode partition(ListNode head, int x) {
        if (head == null||head.next==null) {
            return head;
        }
        ListNode dumpy = new ListNode();
        dumpy.next = head;
        ListNode pre = dumpy;
        ListNode end = null;

        while (head != null) {
            if (head.val < x) {
                ListNode tem = head;
                head = head.next;
                if (pre.next!=tem){
                    tem.next = pre.next;
                }
                pre.next = tem;
                pre = pre.next;

            } else {
                if (end==null){
                    pre.next = head;
                    end= head;
                    head=head.next;
                }else {
                    end.next = head;
                    end=end.next;
                    head=head.next;

                }
            }
        }
        if (end!=null){
            end.next=null;
        }

        return dumpy.next;
    }
}

 

你可能感兴趣的:(LeetCode_Java版,链表,链表,数据结构,leetcode,算法)