题目描述
给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
求解思路
建立一个虚拟节点指向head,辅助解题;
画图体会链表交换的过程,一切都能解释得通。
输入输出示例
代码
/**
* 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 dump = new ListNode(0);
dump.next = head;
ListNode pre = dump;
while(pre.next != null && pre.next.next != null){
ListNode tem = head.next.next;
pre.next = head.next;
head.next.next = head;
head.next = tem;
pre = head;
head = head.next;
}
return dump.next;
}
}