leetcode [#24]

目录

题目

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 space. You may not modify the values in the list, only nodes itself can be changed.


解决方案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/

public class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null) return null;
ListNode p = head;
while(p != null && p.next != null){
int temp = p.next.val;
p.next.val = p.val;
p.val = temp;
p = p.next.next;
}
return head;
}
}

注意事项

  1. 默认链表有偶数个元素。
  2. 遍历整个链表,每两个做交换即可。