24. 两两交换链表中的节点
1.题目描述
2.适用场景
时间复杂度O(n)
3.做题思路
4.代码实现
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dumyhead = new ListNode(-1);
dumyhead.next = head;
ListNode cur = dumyhead;
ListNode temp;
ListNode firstlist;
ListNode seclist;
while(cur.next != null && cur.next.next != null){
temp = cur.next.next.next;
firstlist = cur.next;
seclist = cur.next.next;
cur.next = seclist;
seclist.next = firstlist;
cur = firstlist;
cur.next = temp;
}
return dumyhead.next;
}
}
递归
5.错误总结
return head
while(cur.next != null && cur.next.next != null)
19.删除链表的倒数第N个节点
1.题目描述
2.适用场景
- 时间复杂度: O(n)
- 空间复杂度: O(1)
3.做题思路
4.代码实现
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummylist = new ListNode(-1);
dummylist.next = head;
ListNode fast = dummylist;
ListNode low = dummylist;
for(int i=0; i<=n;i++){
fast = fast.next;
}
while(fast != null){
fast = fast.next;
low = low.next;
}
low.next = low.next.next;
return dummylist.next;
}
}
5.错误总结
for(int i=0; i<=n;i++)