剑指 Offer 25. 合并两个排序的链表
输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。
示例1:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* dummyhead = new ListNode(0);
ListNode* cur = dummyhead;
if(l1==NULL&&l2==NULL) return NULL;
if(l1==NULL&&l2!=NULL) return l2;
if(l1!=NULL&&l2==NULL) return l1;
while(l1!=NULL&&l2!=NULL)
{
if(l1->val<=l2->val)
{
cur->next = l1;
cur = cur->next;
l1 = l1->next;
}
else{
cur->next = l2;
cur = cur->next;
l2 = l2->next;
}
}
if(l1!=NULL) cur->next = l1;
if(l2!=NULL) cur->next = l2;
return dummyhead->next;
}
};
剑指 Offer 52. 两个链表的第一个公共节点
输入两个链表,找出它们的第一个公共节点。
输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
输出:Reference of the node with value = 8
输入解释:相交节点的值为 8 (注意,如果两个列表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,0,1,8,4,5]。在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。
注:比较的是指针而不是val
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
int sum1 = 0;
int sum2 = 0;
ListNode* cur1 = headA;
ListNode* cur2 = headB;
while(cur1!=NULL)
{
sum1++;
cur1=cur1->next;
}
while(cur2!=NULL)
{
sum2++;
cur2=cur2->next;
}
if(sum1>sum2)
{
int k = sum1-sum2;
while(k--)
{
headA = headA->next;
}
}
else{
int k = sum2 - sum1;
while(k--)
{
headB = headB->next;
}
}
while(headA!=headB&&headA!=NULL)
{
headA = headA->next;
headB = headB->next;
}
return headA;
}
};
简便实现
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode* cur1 = headA;
ListNode* cur2 = headB;
while(cur1!=cur2)
{
cur1 = cur1==NULL ? headB : cur1->next;
cur2 = cur2==NULL ? headA : cur2->next;
}
return cur1;
}
};