链表基础02
面试题 02.07. 链表相交
同:160.链表相交
给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点,返回 null 。
图示两个链表在节点 c1 开始相交:
法一:双子针
思路:A先走headA走完走headB到公共点;B先走headB走完再走headA到公共点,两者距离相同;若有公共点则A==B,无则走完;
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode A = headA, B = headB;
while (A != B) {
A = A != null ? A.next : headB;
B = B != null ? B.next : headA;
}
return A;
}
}
法二:哈希
思路:如果当前节点在哈希集合中,则后面的节点都在哈希集合中,即从当前节点开始的所有节点都在两个链表的相交部分,因此在链表 中遍历到的第一个在哈希集合中的节点就是两个链表相交的节点,返回该节点。
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
Set<ListNode> visited = new HashSet<ListNode>();
ListNode temp = headA;
while (temp != null) {
visited.add(temp);
temp = temp.next;
}
temp = headB;
while (temp != null) {
if (visited.contains(temp)) {
return temp;
}
temp = temp.next;
}
return null;
}
}
24. 两两交换链表中的节点
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode pre =new ListNode(0);
pre.next=head;
ListNode temp=pre;
while(temp.next!=null&&temp.next.next!=null){
ListNode start=temp.next;
ListNode end=temp.next.next;
temp.next=end;
start.next=end.next;
end.next=start;
temp=start;
}
return pre.next;
}
}
19.删除链表的倒数第N个节点
力扣题目链接(opens new window)
给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
进阶:你能尝试使用一趟扫描实现吗?
双指针:先让p指针走n个结点,pre指针再从头走,p走到null时,pre就是倒数第n个结点
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0, head);
ListNode pre=dummy;
ListNode p=head;
for(int i=0;i<n;i++){
p=p.next;
}
while(p!=null){
p=p.next;
pre=pre.next;
}
pre.next=pre.next.next;
return dummy.next;
}
}