题目
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
思路
考单链表的题目,交换每相邻两个元素的顺序,这里我们可以通过创建一个头指针(空元素)指向第一个元素。过程如下:
1、创建一个空元素dummy,指向单链表首元素head,并把其设为当前元素cur
2、创建两个指针first和second分别指向当前元素的下一个元素和下下个元素。
3、将first指向second的下一个,second指向first,当前元素cur指向cur的下下个元素
4、返回元素的首元素(空元素的下一个)
代码
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode cur = dummy;
while(cur.next != null && cur.next.next != null){
ListNode first = cur.next;
ListNode second = cur.next.next;
first.next = second.next;
second.next = first;
cur.next = second;
cur = cur.next.next;
}
return dummy.next;
}