鍍金池/ 教程/ Java/ Swap Nodes in Pairs(交換序列中的結(jié)點(diǎn))
ZigZag Conversion(Z型轉(zhuǎn)換)
String to Integer (atoi)(轉(zhuǎn)換到整型)
Generate Parentheses(生成括號(hào))
Longest Common Prefix(最長(zhǎng)公共前綴)
Remove Duplicates from Sorted Array(從已排序數(shù)組中移除重復(fù)元素)
Swap Nodes in Pairs(交換序列中的結(jié)點(diǎn))
Valid Parentheses(有效的括號(hào))
4 Sum(4 個(gè)數(shù)的和)
3 Sum(3 個(gè)數(shù)的和)
3 Sum Closest(最接近的 3 個(gè)數(shù)的和)
Reverse Nodes in k-Group(在K組鏈表中反轉(zhuǎn)結(jié)點(diǎn))
Regular Expression Matching (正則表達(dá)式匹配)
Two Sum
Container With Most Water(最大水容器)
Merge Two Sorted Lists(合并兩個(gè)已排序的數(shù)組)
Remove Nth Node From End of List(從列表尾部刪除第 N 個(gè)結(jié)點(diǎn))
String to Integer (atoi)(轉(zhuǎn)換到整型)
Palindrome Number(回文數(shù))
Longest Substring Without Repeating Characters
Roman to Integer(羅馬數(shù)到整型數(shù))
Integer to Roman(整型數(shù)到羅馬數(shù))
Reverse Integer(翻轉(zhuǎn)整數(shù))
Merge k Sorted Lists(合并 K 個(gè)已排序鏈表)
Implement strStr()(實(shí)現(xiàn) strStr() 函數(shù))
Longest Palindromic Substring(最大回文子字符串)
Add Two Numbers
Letter Combinations of a Phone Number(電話號(hào)碼的字母組合)

Swap Nodes in Pairs(交換序列中的結(jié)點(diǎn))

翻譯

給定一個(gè)鏈表,調(diào)換每?jī)蓚€(gè)相鄰節(jié)點(diǎn),并返回其頭部。

例如,
給定 1->2->3->4, 你應(yīng)該返回的鏈表是 2->1->4->3。

你的算法必須使用唯一不變的空間。

你也不能修改列表中的值,只有節(jié)點(diǎn)本身是可以改變的。

原文

Give 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 作為示例,將其作為兩部分

1,2 -- 3,4

或者我畫(huà)個(gè)圖出來(lái)更加直觀吧……

http://wiki.jikexueyuan.com/project/leetcode-book/images/7.png" alt="" />

代碼

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *    int val;
 *    ListNode* next;
 *    ListNode(int x): val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if(head == NULL) return NULL;
        if(head->next == NULL) return head;

        ListNode* temp = head->next;
        head->next = swapPairs(temp->next);
        temp->next = head;

        return temp;
    }
};