0
点赞
收藏
分享

微信扫一扫

数据结构与算法【LeetCode-Offer】:2.8链表—160. 相交链表


题目描述

​​题目链接​​

数据结构与算法【LeetCode-Offer】:2.8链表—160. 相交链表_leetcode

解题思路

package com.kami.leetcode.list_study;

import com.kami.leetcode.list_study.listNode.ListNode;

/**
* @Description: TODO
* @author: scott
* @date: 2021年12月23日 9:40
*/
public class Solution_86 {
public ListNode partition(ListNode head, int x){
if(head == null || head.next == null){
return head;
}

// 存储小于 x 链表的虚拟头节点
ListNode smallHead = new ListNode(0);
ListNode l1 = smallHead;

// 存储大于等于 x 链表的虚拟头节点
ListNode bigHead = new ListNode(0);
ListNode l2 = bigHead;

//遍历源链表
ListNode cur = head;
while (cur != null){
if(cur.val < x){
l1.next = cur;
l1 = l1.next;
}else {
l2.next = cur;
l2 = l2.next;
}
cur = cur.next;
}

// 合并两个链表
l1.next = bigHead.next;
// 防止出现环
l2.next = null;

return smallHead.next;
}
}


举报

相关推荐

0 条评论