問題:
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->2->3->4,你應該返回鏈表 2->1->4->3。
你的算法應該只使用恒定的空間。你不能修改鏈表中的值,只有節點本身可以被改變。
思路:
題目里把最好用的一種方法禁止了,就是直接交換兩個節點的值就可以了。但也還好做,就交換相鄰節點的next指向的節點就可以了,然后遞歸下去,要注意判斷節點是不是null的情況。不過這種做法一定要創建新的節點來臨時存儲節點,不知道這算不算不遵守題目要求呢。
代碼(Java):
/**
* 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 && head.next != null) {
ListNode next = head.next;
head.next = swapPairs(next.next);
next.next = head;
return next;
} else return head;
}
}
合集:https://github.com/Cloudox/LeetCode-Record