[LeetCode] Swap Nodes in Pairs 解题报告

本文介绍了一种链表相邻节点交换的算法实现,通过双指针互换节点,解决了链表长度为2的边界条件,并提供了递归解法进行简化。

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.

» Solve this problem

[解题思路]
双指针互换,要考虑一些边界条件,比如链表为空,链表长度为1,链表长度为2.
加一个safeGuard可以避开链表长度为2的检测。

[Code]

1:  ListNode *swapPairs(ListNode *head) {   
2: if(head == NULL) return NULL;
3: if(head->next == NULL) return head;
4: ListNode* safeG = new ListNode(-1);
5: safeG->next= head; // head will be changed in next switch
6: ListNode *pre = head->next;
7: ListNode *cur = head;
8: ListNode *post = safeG;
9: while(pre!=NULL)
10: {
11: ListNode* temp = pre->next;
12: pre->next = cur;
13: cur->next = temp;
14: post->next = pre;
15: post= cur;
16: if(post->next == NULL) break;
17: cur = post->next;
18: pre = cur->next;
19: }
20: head = safeG->next;
21: delete safeG;
22: return head;
23: }

Haoran给了一个递归解法,更简洁

1:    ListNode *swapPairs(ListNode *head) {  
2: if (head == NULL || head->next == NULL) {
3: return head;
4: }
5: ListNode* nextPair = head->next->next;
6: ListNode* newHead = head->next;
7: head->next->next = head;
8: head->next = swapPairs(nextPair);
9: return newHead;
10: }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值