Swap Nodes in Pairs -- leetcode
来源:互联网 发布:网络机顶盒刷机通用版 编辑:程序博客网 时间:2024/06/05 07:46
题目描述:
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.
大意是:成对的交换链表的结点,1和2交换;3和4交换,5和6交换等。
/** * 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; ListNode *newList = new ListNode(0); newList->next = head; head = newList; while(head->next != NULL && head->next->next != NULL){ ListNode *p1 = head -> next;//取出第一个节点结点 ListNode *p2 = head -> next -> next;//取出第二个节点结点 // head->p1->p2->... ---->> head->p2->p1->... head -> next = p2; p1 -> next = p2 -> next; p2 -> next = p1; //move head to p1 head = p1; } return newList->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
- 【OpenCV入门教程之十二】OpenCV边缘检测:Canny算子,Sobel算子,Laplace算子,Scharr滤波器合辑
- ajax的同步与异步
- Unity 折叠树 EditorGUI.Foldout
- bzoj 4551: [Tjoi2016&Heoi2016]树 并查集
- VS2015添加Command Prompt 到工具菜单项
- Swap Nodes in Pairs -- leetcode
- CSS实现单行、多行溢出省略号
- windows下编译Matconvnet的方法(CPU和GPU)
- cannot touch `xxx/catalina.out': No such file or directory
- C/C++之类型输出
- JAVA 泛型中的<T> 和 <?> 的应用场景
- CC2640之OAD扩充ImageB大小到44KB
- 多校联赛第八场
- Tomcat下配置solr服务