[LeetCode] Swap Nodes in Pairs
来源:互联网 发布:windows清理助手怎么样 编辑:程序博客网 时间:2024/06/15 18:08
题目:
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) { ListNode *h= (ListNode *)malloc(sizeof(ListNode));h->next = head;if (head == NULL || head->next == NULL){return head;}ListNode *pre = h;ListNode *ptr = pre->next;ListNode *tail = ptr->next;while ( true ){pre->next = tail;ptr->next = tail->next;tail->next = ptr;pre = ptr;if (ptr->next)ptr = ptr->next;elsebreak;if (ptr->next)tail = ptr->next;elsebreak;}return h->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
- ARM学习随笔(10)中断的学习
- poj_1144/uva_315/zoj_1311 Network(割點模板題)
- myeclipse一直停留在Loading workbench界面上的处理办法
- HDU-2112-最短路(map)
- 完全符合能量守恒,胡克定理的JavaScript弹簧振子(超简洁版,超越第一版!)
- [LeetCode] Swap Nodes in Pairs
- BOJ 416. 丁神去谷歌
- 关于Jdk1.5特性 -----黑马程序员
- 还有的是封闭式的方式的合肥市
- hdu1698Just a Hook(线段树区间更新)
- 计算机学院研发第二轮考核--------数据库篇之(删除书签)
- Unity3D研究院之处理角色控制器实现上坡爬坡减速(四十六)
- 关于java图形界面开发下拉框和文本域以及其响应事件
- 快速开发设置界面-----PreferenceActivity