[LeetCode]Swap Nodes in Pairs
2015-07-26 23:10
495 查看
解题思路:
就是前后互换呗,又不让改动val,只能在head前面加一个牵引node,用来操作这一切
就是前后互换呗,又不让改动val,只能在head前面加一个牵引node,用来操作这一切
/** * 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) { ListNode* preHead = new ListNode(0); preHead->next = head; ListNode* cur = preHead; while(cur->next != NULL && cur->next->next != NULL){ ListNode* tmp = cur->next; cur->next = cur->next->next; tmp->next = cur->next->next; cur->next->next = tmp; cur = cur->next->next; } return preHead->next; } };
// Java 实现 public class Solution { public ListNode swapPairs(ListNode head) { ListNode dummyHead = new ListNode(0); ListNode p = dummyHead; ListNode q = head; dummyHead.next = head; while( q != null && q.next != null){ p.next = q.next; q.next = p.next.next; p.next.next = q; q = q.next; p = p.next.next; } return dummyHead.next; } }
相关文章推荐
- 【LeetCode】237 & 203 - Delete Node in a Linked List & Remove Linked List Elements
- [LeetCode]Populating Next Right Pointers in Each Node
- LeetCode-Remove Nth Node From End of List
- Reverse Nodes in k-Group
- leetcode[24]:Swap Nodes in Pairs
- javascrip中parentNode和offsetParent之间的区别
- 【Leetcode】Delete Node in a LinkedList
- [Leetcode 25] Reverse Nodes in k-Group
- leetcode[117]:Populating Next Right Pointers in Each Node II
- windows下关于nodejs和npm的安装、方法,网址
- 理解inode
- leetcode[116]:Populating Next Right Pointers in Each Node
- 我的第一个Node web程序
- Node.js模板引擎学习----ejs
- Hadoop学习笔记(老版本,YARN之前),MapReduce任务Namenode DataNode Jobtracker Tasktracker之间的关系
- Leetcode 19 Remove Nth Node From End of List
- Nodejs总结
- Nodejs进程管理模块forever详解
- leetcode - Swap Nodes in Pairs
- 237、Delete Node in a Linked List [Leetcode]