今日任务
- 24. 两两交换链表中的节点
- 19.删除链表的倒数第N个节点
- 面试题 02.07. 链表相交
- 142.环形链表II
- 总结
LeetCode24 两两交换链表中的节点
题目链接:24.交换节点
思路:
● 在206反转链表中,由于进行的是pre和cur之间的指针改变,只需用一个临时节点tmp保存cur.next
● 在这道题中是同样的步骤:①设置临时指针②画图,更改节点指向③移动指针,进行下一步操作
画图能够更加清楚地看出需要更改的步骤,临时指针的设定则更便于第三步移动指针的操作。
(1)普通解法:
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(-1,head);
ListNode pre = dummy;
//先声明再赋值
ListNode tmp;
ListNode cur1;
ListNode cur2;
//xx.next: xx!=null条件
while(pre.next!=null && pre.next.next!=null){
//临时指针
cur1 = pre.next;
cur2 = pre.next.next;
tmp = pre.next.next.next;
//更改指向
pre.next = cur2;
cur2.next = cur1;
cur1.next = tmp;
//pre指针移动
pre = cur1;
}
return dummy.next;
}
}
(2)递归法
class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null)
return head;
// 获取当前节点的下一个节点
ListNode cur = head;
ListNode next = head.next;
// 进行递归
ListNode newNode = swapPairs(next.next);
// 这里进行交换
next.next = cur;
cur.next = newNode;
return next;
}
}
LeetCode19 删除链表中第N个节点
题目链接:19. 删除链表中第N个节点
思路:快慢指针法,为了使慢指针指向倒数第n节点的前一个节点,即倒数第n+1个节点
快指针要先走n+1,再快慢指针同时移动直到快指针=null
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummyhead = new ListNode(-1, head);
ListNode slow = dummyhead;
ListNode fast = dummyhead;
for (int i = 0; i <= n; i++) {
fast = fast.next;
}
while (fast != null) {
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return dummyhead.next;
}
}
LeetCode面试02.07 链表相交
题目链接: 面试02.07 链表相交
思路:先计算两个链表的长度,让二者指向末尾对齐的位置,然后再遍历比较。
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
int num1 = 1;
int num2 =1;
ListNode cur1 = headA;
ListNode cur2 = headB;
while(cur1 != null){
cur1 = cur1.next;
num1 += 1;
}
while(cur2 != null){
cur2 = cur2.next;
num2 += 1;
}
//重新初始化,从最后一个节点开始移动两指针,比较指向的节点是否一致
cur1 = headA;
cur2 = headB;
if(num1>num2){
for(int i=0;i<Math.abs(num1-num2);i++){
cur1=cur1.next;
}
}
else{
for(int j=0;j<Math.abs(num1-num2);j++){
cur2=cur2.next;
}
}
while(cur1!=null){
if(cur1 == cur2){
return cur1;
}else{
cur1=cur1.next;
cur2=cur2.next;
}
}
return null;
}
}
LeetCode142 环形链表ii
题目链接:142.环形链表
思路:两步
(1)判断是否有环:快慢指针法,快指针走两步,慢指针走一步,判断是否会相遇;
(2)如果有环,从哪里开始入环。根据一些数学运算可知,当n=1时,x=z,即从头结点和相遇节点出发,以同样每次走一个节点的速度,二者将在环形出口节点相遇
因此,代码可以这样写:
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
//不满足非null条件说明有界无环
while(fast!= null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
if(fast == slow){ //直到fast、slow在环上相遇
//接着一个从head出发,一个从相遇处出发,他们最终会在入环初相遇
ListNode index1 = head;
ListNode index2 = slow;
while(index1 != index2){
index1 = index1.next;
index2 = index2.next;
}
return index1;
}
}
return null;
}
}
01/14感想:
终于赶上进度了哈哈哈哈!我爱休息日!找个时间总结一下链表和数组
这两天冲冲把小论文也改好投了(晕)~