剑指Offer第十二天
链表(简单)
感觉链表还是有点生疏啊
题1:合并两个排序的链表
输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null && l2== null){
return null;
}
ListNode newNode = new ListNode(-1);
ListNode point = newNode;
while(l1!=null && l2!=null) {
if(l1.val <= l2.val){
newNode.next = l1;
l1 = l1.next;
} else {
newNode.next = l2;
l2 = l2.next;
}
newNode = newNode.next;
}
if(l1 != null) {
newNode.next = l1;
}
if(l2 != null) {
newNode.next = l2;
}
return point.next;
}
}
题2:两个链表的第一个共同节点
好烦啊,做过一次还是忘了怎么写。。
/**
* 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 pointA = headA;
ListNode pointB = headB;
while(pointA != pointB){
pointA = pointA==null?headB:pointA.next;
pointB = pointB==null?headA:pointB.next;
}
return pointA;
}
}