代码随想录第四天|链表| 24. 两两交换链表中的节点 |19.删除链表的倒数第N个节点|02.07. 链表相交
题目:24. 两两交换链表中的节点 - https://leetcode.cn/problems/swap-nodes-in-pairs/
文章学习链接:https://programmercarl.com/0024.两两交换链表中的节点.html
题目: 19.删除链表的倒数第N个节点 - https://leetcode.cn/problems/remove-nth-node-from-end-of-list/
文章学习链接:https://programmercarl.com/0019.删除链表的倒数第N个节点.html
题目:02.07. 链表相交 - https://leetcode.cn/problems/intersection-of-two-linked-lists-lcci/description/
文章学习链接:https://programmercarl.com/面试题02.07.链表相交.html
24. 两两交换链表中的节点
题目内容:给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
解题代码
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummyNode = new ListNode();
dummyNode.next = head;
ListNode pre = dummyNode.next;
ListNode last;
ListNode ans = dummyNode;
ListNode temp;
while(pre != null && pre.next!=null){
last = pre.next;
temp = last.next;
ans.next = last;
ans.next.next = pre;
ans = ans.next.next;
pre.next = null;
pre = temp;
}
if(pre!=null){
ans.next = pre;
}
return dummyNode.next;
}
}
19.删除链表的倒数第N个节点
题目内容:给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
解题代码
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dumpNode = new ListNode();
dumpNode.next = head;
ListNode fast = dumpNode;
ListNode slow = dumpNode;
for(int i = 0;i< n;i++){
fast = fast.next;
}
while(fast.next != null){
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return dumpNode.next;
}
}
02.07. 链表相交
题目内容:给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点,返回 null 。
解题代码
class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode curA = headA;
ListNode curB = headB;
if(headA == null || headB == null){
return null;
}
while(curB != null){
if( curA == curB){
return curA;
}
if(curA.next != null){
curA = curA.next;
continue;
}
curA = headA;
curB = curB.next;
}
return null;
}
}

浙公网安备 33010602011771号