160. 相交链表https://leetcode-cn.com/problems/intersection-of-two-linked-lists/
注意:题目不仅要求公共节点值相等,地址也要相等!!!
第一版
- 先确认哪一个链表更长,所以写了一个length()函数用来求长度,然后定义两个指针,长指针和短指针,再算出链表长度之差dist;
- 让长指针先走dist长度,再长、短指针同步移动,如果碰到两个指针相等,就找到了公共节点,否则就null。
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
int alen = length(headA),blen = length(headB);
ListNode longl,shortl;
int dist=0;//
if(alen > blen){
longl = headA;
shortl = headB;
dist = alen - blen;
}else{
shortl = headA;
longl = headB;
dist = blen - alen;
}
while(dist>0){
longl = longl.next;
dist--;
}
while(longl!=null){
if(longl==shortl)
return longl;
else{
longl = longl.next;
shortl = shortl.next;
}
}
return null;
}
public int length(ListNode head){
int length=0;
while(head!=null){
length++;
head = head.next;
}
return length;
}
}
第二版 (看的答案,绝绝子)
-
链表 headA 和 headB 的长度分别是 m 和 n。假设链表 headA 的不相交部分有 a 个节点,链表headB 的不相交部分有 b个节点,两个链表相交的部分有 c 个节点,则有 a+c=m,b+c=n。
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) {
return null;
}
ListNode pA = headA, pB = headB;
while (pA != pB) {
pA = pA == null ? headB : pA.next;
pB = pB == null ? headA : pB.next;
}
return pA;
}
}
82. 删除排序链表中的重复元素 IIhttps://leetcode-cn.com/problems/remove-duplicates-from-sorted-list-ii/
存在一个按升序排列的链表,给你这个链表的头节点
head
,请你删除链表中所有存在数字重复情况的节点,只保留原始链表中 没有重复出现 的数字。输入:head = [1,2,3,3,4,4,5] 输出:[1,2,5]
思路:
-
几乎所有的链表题目,都具有相似的解题思路。
-
建一个「虚拟头节点」ans 以减少边界判断,往后的答案链表会接在 node 后面,使用 node 代表当前有效链表的结尾,通过原输入的 head 指针进行链表扫描,
-
我们会确保「进入外层循环时 head 不会与上一节点相同」,因此插入时机:
-
head 已经没有下一个节点,head 可以被插入
-
head 有一下个节点,但是值与 head 不相同,head 可以被插入
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode ans = new ListNode(0);
ListNode node = ans;
while(head!=null){
if(head.next==null|| head.next.val!=head.val){
node.next = head;
node =head;
}
while(head.next!=null&& head.next.val==head.val)
head = head.next;
head = head.next;
}
node.next=null;
return ans.next;
}
}
83. 删除排序链表中的重复元素https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/
- 如果问题变为「相同节点保留一个」,该如何实现?
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (head == null) return head;
ListNode dummy = new ListNode(-109);
ListNode tail = dummy;
while (head != null) {
// 值不相等才追加,确保了相同的节点只有第一个会被添加到答案
if (tail.val != head.val) {
tail.next = head;
tail = tail.next;
}
head = head.next;
}
tail.next = null;
return dummy.next;
}
}