LeetCode 24 两两交换链表中的节点
给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。
你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
输入:head = [1,2,3,4]
输出:[2,1,4,3]
自己想不明白去看了视频,看完视频之后的思路:
1.首先确定循环终止情况,
第一种链表元素个数为奇数时,需要判断cur.next.next为null终止循环。
第二种链表元素为偶数时,要判断cur.next为null时终止循环。
2.确定交换过程,有虚拟头结点真的方便了很多,不用对头结点单独分类写代码。
最重要的步骤应该是,保存cur.next 和 cur.next.next.next 防止后边改完之后节点丢失。
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(0,head);
ListNode cur = dummy;
ListNode temp;
ListNode temp1;
while(cur.next != null && cur.next.next != null){
temp = cur.next;
temp1 = cur.next.next.next;
cur.next = cur.next.next;
cur.next.next = temp;
temp.next = temp1;
cur = cur.next.next;
}
return dummy.next;
}
}
LeetCode 19 删除链表的倒数第 N 个节点
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0,head);
ListNode fast = dummy;
ListNode slow = dummy;
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 dummy.next;
}
}
LeetCode 面试题 02.07 链表相交
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode curA = headA;
ListNode curB = headB;
int LenA = 0 , LenB = 0;
while(curA != null){
LenA++;
curA = curA.next;
}
while(curB != null){
LenB++;
curB = curB.next;
}
curA = headA;
curB = headB;
if(LenA < LenB){
int LenT = LenA ;
LenA = LenB;
LenB = LenT;
ListNode T = curA;
curA = curB;
curB = T;
}
int gap = LenA - LenB;
for(int i = 0; i<gap ; i++){
curA = curA.next;
}
while(curA != null){
if(curA == curB){
return curA;
}
curA = curA.next;
curB =curB.next;
}
return null;
}
}