leetcode 24

LeetCode 24.Swap Nodes in Pairs

题目

Given a linked list, swap every two adjacent nodes and return its head.

Example

1
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.

解题思路:

以Example为例:

JAVA代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null || head.next==null )
return head;
ListNode temp1=head.next;
head.next=temp1.next;
temp1.next=head;
head=temp1;
temp1=head.next;
while(temp1.next!=null && temp1.next.next!=null){
ListNode temp2=temp1.next;
temp1.next=temp2.next;
temp2.next=temp1.next.next;
temp1.next.next=temp2;
temp1=temp2;
}
return head;
}
}