24、Swap Nodes in Pairs
2015-01-23 15:52
211 查看
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.
Linked List
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.
Linked List
ListNode *swapPairs(ListNode *head) { //交换临近节点,不需要额外空间,不能修改节点中的值 ListNode *headL = NULL, *first = NULL, *second = NULL, *next = NULL, *pre = NULL; //确定头结点 if (head) headL = first = head; if (head && head -> next) headL = second = head -> next; while (first && second) { next = second -> next; if (pre) pre -> next = second; second -> next = first; first -> next = next; pre = first; first = next; if (first) second = first -> next; } return headL; }
相关文章推荐
- leetcode 24 Swap Nodes in Pairs
- [leetcode 24]Swap Nodes in Pairs-----成对翻转链表中的节点
- LeetCode24 Swap Nodes in Pairs 25. Reverse Nodes in k-Group详解
- LeetCode 24:Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- LeetCode 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- Leetcode: 24. Swap Nodes in Pairs
- [LeetCode-Algorithms-24] "Swap Nodes in Pairs" (2017.11.7-WEEK10)
- 24. Swap Nodes in Pairs
- LeetCode(24)Swap Nodes in Pairs
- LeetCode之24----Swap Nodes in Pairs
- leetcode 24 Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- Leetcode_24_Swap Nodes in Pairs
- 【LeetCode】24.Swap Nodes in Pairs
- Leetcode 24 Swap Nodes in Pairs
- leetcode-24 Swap Nodes in Pairs
- LeetCode - 24. Swap Nodes in Pairs
- LeetCode24 - swap nodes in pairs