translation
1->2->3->42->1->4->3。你的算法必须使用唯一不变的空间。你也不能修改列表中的值,只有节点本身是可以改变的。
Original
Give a linkedList, swapeveryAdjacent nodes and return itsHead. For example, Given1-2-3-4, you shouldreturn the List as 2-1-4-3.Your algorithm should use onlyconstant Space. May notModify theValuesinch the List, only nodes itself can is changed.
Analysis
Let's take the example of the 1,2,3,4 given in the topic as a two-part
1,2--3,4
Or I'll draw a diagram to make it more intuitive ...
Code
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode* next; * ListNode(int x): val(x), next(NULL) {} * }; */class Solution {public: swapPairs(ListNode* head) { ifreturn NULL; ifreturn head; ListNode* temp = head->next; head->next = swapPairs(temp->next); temp->next = head; return temp; }};
Copyright NOTICE: This article is nomasp Couvant original article, without permission is prohibited reprint! Welcome to my blog: http://blog.csdn.net/nomasp
Leetcode Swap Nodes in Pairs