【双指针】 LCR 023. 相交链表

LCR 023. 相交链表

  • 拆分链表
  • 一个链表元素全部小于x
  • 另一个链表元素全部大于或者等于x
  • 合并链表
/**
 * 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) {
        // 拆分链表  一个全部小于x 另外一个链表元素都大于等于x  然后合并链表
        ListNode list1 = new ListNode(-1);
        ListNode list2 = new ListNode(-1);

        ListNode p1 = list1;
        ListNode p2 = list2;
        ListNode p = head;

        // 遍历当前链表
        while(p != null){
            

            if(p.val >= x){
                ListNode temp = new ListNode(p.val);
                p2.next = temp;
                p2 = p2.next;
            }else{
                ListNode temp = new ListNode(p.val);
                p1.next = temp;
                p1 = p1.next;
            }


            // 然后p指针前进
            p = p.next;
        }

        p1.next = list2.next;


        return list1.next;
    }
}

你可能感兴趣的:(#,Leetcode,链表,数据结构)