剑指offer——第十二天
作者:互联网
剑指offer——第十二天
第一题:剑指 Offer 25. 合并两个排序的链表
问题描述
思路
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode dummyHead = new ListNode(-1), pre = dummyHead;
while (l1 != null && l2 != null) {
if (l1.val <= l2.val) {
pre.next = l1;
pre = pre.next;
l1 = l1.next;
} else {
pre.next = l2;
pre = pre.next;
l2 = l2.next;
}
}
if (l1 != null) {
pre.next = l1;
}
if (l2 != null) {
pre.next = l2;
}
return dummyHead.next;
}
}
第一题:剑指 Offer 52. 两个链表的第一个公共节点
问题描述
思路
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode cur = headB;
if(headA == null || headB == null) return null;
while(headA != null && headB != null && headA != headB){
headB = headB.next;
if(headB == null) {
headA = headA.next;
headB = cur;
}
if(headA == null) return null;
}
return headA;
}
}
标签:pre,ListNode,offer,next,headB,headA,第十二天,null 来源: https://blog.csdn.net/m0_48869571/article/details/121124900