Given a linked list, swap every two adjacent nodes and return its head.
Example:
Given1->2->3->4
, you should return the list as2->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.
迭代,记得画个图,不然会懵逼
/** * 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 dummy = new ListNode(-1), pre = dummy; dummy.next = head; while (pre.next !=null && pre.next.next!=null) {//注意leetcode给的linked list,head已经包含了有用内容。 ListNode swap1 = pre.next; ListNode swap2 = pre.next.next; pre.next = swap2; swap1.next = swap2.next; swap2.next = swap1; pre = swap1; } return dummy.next; } }