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) {
ListNode dummy = new ListNode(-1,head);
ListNode prev = dummy;
while(prev.next != null && prev.next.next != null){
ListNode temp = head.next.next;
prev.next = head.next;
head.next.next = head;
head.next = temp;
prev = head;
head = head.next;
}
return dummy.next;
}
}
19.删除链表的倒数第N个节点
思路:双指针的典型应用。