题目链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs/
题目如下:
思路:
/**
* 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) {
//tip:
//1、当整个操作过程中,头节点会发生变动时,可增加一个虚拟节点
//2、操作中三个指针普遍适用
//3、链表按着顺序来,从后往前,确保不会出错
//4、链表题要画图
if(head==null||head.next==null) return head;//链表中元素仅有0或1个
ListNode dummyhead=new ListNode(0);
dummyhead.next=head;
ListNode p=dummyhead;
while(p.next!=null&&p.next.next!=null){
ListNode node1=p.next;//链表节点数>=2个
ListNode node2=p.next.next;
System.out.println(node1.val);
node1.next=node2.next;
node2.next=node1;
p.next=node2;
//dummyhead->node1->node2 before
//dummyhead->node2->node1 after
p=node1;
}
return dummyhead.next;
}
}