链表的相关知识:
力扣: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) {
// 我的方法,有点复杂,定义了三个指针 pre,cur,temp
// ListNode cur = new ListNode();
// ListNode pre = new ListNode();
// ListNode dummyHead = new ListNode();
// ListNode temp = new ListNode();
// dummyHead.next = head;
// pre= dummyHead;
// if(head == null){
// return null;
// }
// cur = head;
// while(cur!= null && cur.next != null ){
// temp = cur.next.next;
// pre.next = cur.next;
// cur.next.next = cur;
// pre = cur;
// pre.next = temp;
// cur = temp;
// }
// return dummyHead.next;
//代码随想录方法
ListNode cur = new ListNode();
ListNode temp = new ListNode();
ListNode temp1 = new ListNode();
ListNode dummyHead = new ListNode();
dummyHead.next = head;
cur = dummyHead;
while(cur.next != null && cur.next.next != null){
temp = cur.next.next.next;
temp1 = cur.next;
cur.next = cur.next.next;
cur.next.next = temp1;
cur.next.next.next = temp;
cur = cur.next.next;
}
return dummyHead.next;
}
}
总结:1.分析题目,为什么交换的是两两的节点?
如果是交换三个节点,方法是一样的吗?
2.我的方法和代码随想录的方法区别?
核心思想没变,都是用temp来储存中间的指针.
我的方法更复杂!
力扣:19.删除链表的倒数第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 dummyHead = new ListNode();
ListNode left = new ListNode();
ListNode right = new ListNode();
dummyHead.next = head;
left = dummyHead;
right = dummyHead;
while(n>=0){
right = right.next;
n--;
}
// for(int i = 0;i <= n; i++){
// right = right.next;
// }
while(right != null){
left = left.next;
right = right.next;
}
left.next = left.next.next;
return dummyHead.next;
}
}
这道题思路就是双指针,但是要明白:
删除倒数第几个节点,那么左右指针的中间的间隔相差n个。那么right指针走n+1步。因为right节点的最终是最后节点的null;