[LeetCode] Swap Nodes in Pairs
来源:互联网 发布:加拿大28百分百中算法 编辑:程序博客网 时间:2024/05/30 20:07
题目:
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.
解答:/** * 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; } else { ListNode *first, *second, *newHead = NULL, *pre = NULL; first = head; //second = head -> next; while(first != NULL && first -> next != NULL) { second = first -> next; if(newHead == NULL) { newHead = second; } first -> next = second -> next; second -> next = first; if(pre != NULL) { pre -> next = second; } pre = first; first = first -> next; } return newHead; } }};
思路:
这道题没什么难度,容易忽略的就是只使用两个指针,即指向需要调换的两个元素,这样做是不够的,比如1→2→3→4,第一次调换为2→1→3→4,这时候两个指针应该指向3和4了,但是3、4调换完毕后,1的next仍指向3,导致错误,所以需要第三个指针,指向当前需要调换的两个元素的前一个元素,以便做好next的设置。
0 0
- LeetCode:Swap Nodes in Pairs
- LeetCode: Swap Nodes in Pairs
- [Leetcode] Swap Nodes in Pairs
- LeetCode : Swap Nodes in Pairs
- [LeetCode] Swap Nodes in Pairs
- Leetcode: Swap nodes in pairs
- [LeetCode]Swap Nodes in Pairs
- [LeetCode]Swap Nodes in Pairs
- LeetCode-Swap Nodes in Pairs
- LeetCode - Swap Nodes in Pairs
- LeetCode | Swap Nodes in Pairs
- 【leetcode】Swap Nodes in Pairs
- Leetcode: Swap Nodes in Pairs
- LeetCode - Swap Nodes in Pairs
- 【LeetCode】Swap Nodes in Pairs
- Leetcode: Swap Nodes in Pairs
- Leetcode Swap Nodes in Pairs
- LeetCode Swap Nodes in Pairs
- PHP 之 类
- 那些古装美女谁更美
- 收拾心情,重新上路
- swing获取网络图片,并压缩显示
- 网站被黑客扫描撞库该怎么应对防范?
- [LeetCode] Swap Nodes in Pairs
- 作用域
- iOS获取某一时间点视频桢截图
- virtualbox 中主机的上网设置
- J2EE——2014.5.24
- LeetCode OJ - Gas Station
- strong and weak 强引用和弱引用的区别
- C/C++ 内存分配方式,堆区,栈区,new/delete/malloc/free
- 二叉树的链式存储与实现(C++)