We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent ded9ecf commit ac735d9Copy full SHA for ac735d9
problems/0024.两两交换链表中的节点.md
@@ -94,8 +94,21 @@ C:
94
* struct ListNode *next;
95
* };
96
*/
97
+//递归版本
98
+struct ListNode* swapPairs(struct ListNode* head){
99
+ //递归结束条件:头节点不存在或头节点的下一个节点不存在。此时不需要交换,直接返回head
100
+ if(!head || !head->next)
101
+ return head;
102
+ //创建一个节点指针类型保存头结点下一个节点
103
+ struct ListNode *newHead = head->next;
104
+ //更改头结点+2位节点后的值,并将头结点的next指针指向这个更改过的list
105
+ head->next = swapPairs(newHead->next);
106
+ //将新的头结点的next指针指向老的头节点
107
+ newHead->next = head;
108
+ return newHead;
109
+}
110
-
111
+//迭代版本
112
struct ListNode* swapPairs(struct ListNode* head){
113
//使用双指针避免使用中间变量
114
typedef struct ListNode ListNode;
0 commit comments