Given a linked list, swap every two adjacent nodes and return its head.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
Note:
Your algorithm should use only constant extra space.
You may not modify the values in the list's nodes, only nodes itself may be changed.
题目的主要意思:在不修改结点值和可以另外开辟空间的前提下将列表中两两变量互换位置。虽然修改结点值也可以过,但是始终不合要求,也辜负了题目想要考我们链表的基本操作的心愿。
这题对于不熟悉链表的人是一个很好的题目,因为如果捋不清链表元素交换位置后前后各元素的变化,真的看个代码都看到头晕,下面我以我自己看到的一种比较好理解的方法来讲解这道题的一个很简单的思路。
例:A->B->C->D,假设我们要交换B和C的位置,那么此时链表有3个最基本的操作:
1、A指向C
2、B指向D
3、C指向B
完成了上面3个基本操作,也就换成了B和C的互换,但是为了能够继续交换下去,此时指向A的指针要往后移两位。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode preNode=new ListNode(0);
preNode.next=head;
ListNode temp=preNode;
while(temp.next != null && temp.next.next != null){
ListNode node1=temp.next;//B
ListNode node2=temp.next.next;//C
temp.next=node2;//A->C
node1.next=node2.next;//B->D
node2.next=node1;//C->B
temp=temp.next.next;
}
return preNode.next;
}
}