問(wèn)題:
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.
大意:
給出一個(gè)鏈表咧七,交換每?jī)蓚€(gè)相鄰的節(jié)點(diǎn)然后返回頭節(jié)點(diǎn)诚亚。
例子:
給出 1->2->3->4,你應(yīng)該返回鏈表 2->1->4->3咽弦。
你的算法應(yīng)該只使用恒定的空間。你不能修改鏈表中的值带斑,只有節(jié)點(diǎn)本身可以被改變嘶朱。
思路:
題目里把最好用的一種方法禁止了配并,就是直接交換兩個(gè)節(jié)點(diǎn)的值就可以了。但也還好做厦瓢,就交換相鄰節(jié)點(diǎn)的next指向的節(jié)點(diǎn)就可以了提揍,然后遞歸下去啤月,要注意判斷節(jié)點(diǎn)是不是null的情況。不過(guò)這種做法一定要?jiǎng)?chuàng)建新的節(jié)點(diǎn)來(lái)臨時(shí)存儲(chǔ)節(jié)點(diǎn)劳跃,不知道這算不算不遵守題目要求呢谎仲。
代碼(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