Swap Nodes in Pairs
2013-12-26 16:34
85 查看
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
这个问题我们先建一个头结点,这样可以统一操作,每一步就那么几个操作,见图。
这样就不用特别处理第一结点,好了看明白这个图说的步骤就代码。
leetcode里有好多链表题,这里是创建链表的函数,想自己测试的在这里下:创建链表函数
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.
这个问题我们先建一个头结点,这样可以统一操作,每一步就那么几个操作,见图。
这样就不用特别处理第一结点,好了看明白这个图说的步骤就代码。
class Solution { public: ListNode *swapPairs(ListNode *head) { if(head == NULL || head->next == NULL) return head; ListNode *pre, *tail; ListNode *new_head = new ListNode(-1); new_head->next = head; pre = new_head; while(pre->next && pre->next->next) { tail = pre->next->next; pre->next->next = tail->next; tail->next = pre->next; pre->next = tail; pre = tail->next; } pre = new_head; new_head = new_head->next; delete pre; return new_head; } };
leetcode里有好多链表题,这里是创建链表的函数,想自己测试的在这里下:创建链表函数
相关文章推荐
- LeetCode | Swap Nodes in Pairs
- eetcode_c++:链表:Swap Nodes in Pairs(024)
- LeetCode Algorithms #24 <Swap Nodes in Pairs>
- 【Leetcode】Swap Nodes in Pairs
- [LeetCode]Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- leetcode24:Swap Nodes in Pairs
- 24 Swap Nodes in Pairs
- 【Leetcode】Swap Nodes in Pairs
- [LeetCode]Swap Nodes in Pairs
- Swap Nodes in Pairs--LeetCode
- [leetcode 26] Swap Nodes in Pairs
- 第四周算法分析与设计:Swap Nodes in Pairs
- leetcode-024 Swap Nodes in Pairs
- Swap Nodes in Pairs
- [LeetCode] Swap Nodes in Pairs
- 算法分析与设计——LeetCode:24. Swap Nodes in Pairs
- 第61题 Swap Nodes in Pairs
- Swap Nodes in Pairs
- Leetcode题解-24. Swap Nodes in Pairs