Swap Nodes in Pairs
2017-01-11 00:10
344 查看
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.
Subscribe to see which companies asked this question
这道题,要了解链表之间的插入和调换,要交换两个指针,需要三个指针(需要一个头指针,两个节点各一个指针),这是必须要知道的。而且由于head指针里有数据,所以必须创建一个空指针将连接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.
Subscribe to see which companies asked this question
这道题,要了解链表之间的插入和调换,要交换两个指针,需要三个指针(需要一个头指针,两个节点各一个指针),这是必须要知道的。而且由于head指针里有数据,所以必须创建一个空指针将连接head,这个空指针作为第一次循环的头指针。
/** * 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) return head; ListNode new_head(-1); new_head.next=head; ListNode* N=&new_head; ListNode* p=N->next; ListNode* q=N->next->next; while(q&&p){ N->next=q; p->next=q->next; q->next=p; if(p->next){ N=N->next->next; p=N->next; q=N->next->next; } else break; } return new_head.next; } };
相关文章推荐
- LeetCode - Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- LeetCode--Swap Nodes in Pairs
- LeetCode 24. Swap Nodes in Pairs(按对交换单链表结点)
- [Leetcode]24. Swap Nodes in Pairs
- LeetCode刷题——Swap Nodes in Pairs(Medium)
- [LeetCode] 24. Swap Nodes in Pairs
- Leetcode 24. Swap Nodes in Pairs (Easy) (cpp)
- LeetCode 24_Swap Nodes in Pairs
- Swap Nodes in Pairs刷题历程
- Swap Nodes in Pairs
- [LeetCode][链表]Swap Nodes in Pairs
- Leetcode 24 Swap Nodes in Pairs
- Swap Nodes in Pairs
- 【LeetCode】24. Swap Nodes in Pairs
- [Leetcode] 24. Swap Nodes in Pairs
- LeetCode Online Judge 题目C# 练习 - Swap Nodes in Pairs
- Leetcode_swap-nodes-in-pairs(c++ and python version)
- LeetCode-24-Swap-Nodes-in-Pairs 链表递归水题
- LeetCode之旅(21)-Swap Nodes in Pairs