leetcode--Swap Nodes in Pairs
来源:互联网 发布:mac安装oracle 11g 编辑:程序博客网 时间:2024/06/04 17:58
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.
解题思路
成对调换链表中的元素。
方法一:
我们直接换掉两个相邻节点的val属性即可。但是题目要求You may not modify the values in the list,虽然如此,我还是实现了这样的算法,简单快捷,为什么不呢。
class Solution {public: ListNode* swapPairs(ListNode* head) { if(head==NULL) return NULL; if(head->next==NULL) return head; ListNode* p=head,*s; int flag=0; while(p&&p->next) { s=p->next; int temp=p->val; p->val=s->val; s->val=temp; p=s->next; } return head; }};
方法二
因为不能直接交换两个节点的值,只能改变节点的next,我们仿照方法一,继续交换,不过是通过改变next来实现的,代码如下。
class Solution {public: ListNode* swapPairs(ListNode* head) { if(head==NULL) return NULL; if(head->next==NULL) return head; ListNode* addNode=new ListNode(0);//为了让头结点跟其他节点一样,同样处理,增加一个节点指向头结点。 addNode->next=head; ListNode *cur; for(cur=addNode;cur->next!=NULL&&cur->next->next!=NULL;cur=cur->next->next) { cur->next=swap(cur->next,cur->next->next); } head=addNode->next; return head; } ListNode* swap(ListNode* p,ListNode* q) { p->next=q->next; q->next=p; return q; }};
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
- eCosBox使用说明(1)——快速入门
- SGU 100. A+B
- 第九周项目4——我的向量类
- Android Executor 如何实现任务Runnable队列顺序执行
- Socket层实现系列 — 睡眠驱动的同步等待
- leetcode--Swap Nodes in Pairs
- 解决linux下matlab中文乱码问题
- 第四周——字符类型判断
- InstallShield 操作整理
- C++作业6.12
- 黑客与画家读书笔记
- QTableView与QTableWidget高阶使用积累
- 详细解细JAVA的数据结构
- 采用dlopen、dlsym、dlclose加载动态链接库【总结】