LeetCode--Swap Nodes in Pairs
2017-07-26 11:32
435 查看
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.
方法一:递归法。每次交换前两个,并递归调用交换后面的,交换后面的时候也是先交换前两个,直到不能交换。
方法二:定义一个辅助的头结点和头指针(会发现很方便)。直接正向思维,交换每相邻的两个节点,记录第三个节点更新给当前的头指针的下一个即可,这里的头指针每次都是更新为待交换两个节点前的那个。
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.
方法一:递归法。每次交换前两个,并递归调用交换后面的,交换后面的时候也是先交换前两个,直到不能交换。
/** * 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||head->next==NULL) return head; ListNode* newhead=head->next; head->next=swapPairs(newhead->next); newhead->next=head; return newhead; } };
方法二:定义一个辅助的头结点和头指针(会发现很方便)。直接正向思维,交换每相邻的两个节点,记录第三个节点更新给当前的头指针的下一个即可,这里的头指针每次都是更新为待交换两个节点前的那个。
/** * 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||head->next==NULL) return head; ListNode dummy(0); ListNode *cur=&dummy; while(head&&head->next){ ListNode *next=head->next->next; cur->next=head->next; cur=cur->next; cur->next=head; cur=cur->next; head->next=NULL; head=next; } if(head) cur->next=head; return dummy.next; } };
相关文章推荐
- [Leetcode] Swap Nodes in Pairs
- Leetcode Swap Nodes in Pairs
- 【C++】【LeetCode】24. Swap Nodes in Pairs
- leetcode-24-Swap Nodes in Pairs
- LeetCode | Swap Nodes in Pairs
- Java [leetcode 24]Swap Nodes in Pairs
- LeetCode 24. Swap Nodes in Pairs
- leetcode--24. Swap Nodes in Pairs
- Leetcode 24. Swap Nodes in Pairs
- Swap Nodes in Pairs--LeetCode
- [Leetcode 24 链表]Swap Nodes in Pairs
- [LeetCode]--24. Swap Nodes in Pairs
- LeetCode 024 Swap Nodes in Pairs
- LeetCode——Swap Nodes in Pairs
- Leetcode 24. Swap Nodes in Pairs
- [LeetCode 024] Swap Nodes in Pairs
- [LeetCode]Swap Nodes in Pairs
- [Leetcode]Swap Nodes in Pairs
- LeetCode—Swap Nodes in Pairs
- leetcode 题解 || Swap Nodes in Pairs 问题