思路:创建一个新链表,分别遍历两个链表。两个链表中的较小结点添加到新链表。若链表l1未遍历完,将剩余结点添加到新链表;若l2未遍历完,将l2剩余结点添加至新链表。
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode head = new ListNode(-1);
ListNode node = head;
while (l1!=null && l2!=null){
if (l1.val < l2.val){
node.next = l1;
node = node.next;
l1 = l1.next;
}else{
node.next = l2;
node = node.next;
l2 = l2.next;
}
}
if (l1!=null){
node.next = l1;
}
if (l2!=null){
node.next = l2;
}
return head.next;//第一个元素是-1
}
思路:这个看了评论才有思路。假设交集链表的长度为c;链表A除了交集的长度为a;链表B除了交集的长度为b。则有这个等式:a+c+b = b+c+a。即链表A从头遍历,遍历至尾部时(null),从链表B头节点开始遍历;链表B从头遍历,遍历至尾部时(null),从链表A头节点开始遍历。则同时到达交集链表;若无交集,则同时遍历至null。
ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null)
return null;
ListNode node1 = headA,node2 = headB;
while (node1!=node2){
node1 = node1==null?headB:node1.next;
node2 = node2==null?headA:node2.next;
}
return node1;
}
该文介绍了两种链表操作的解决方案:一是合并两个已排序的链表,通过创建新链表并比较两个链表节点值来实现;二是找到两个链表的第一个公共节点,利用循环和链表长度差来定位交集。
1480

被折叠的 条评论
为什么被折叠?



