24. Swap Nodes in Pairs
来源:互联网 发布:木子软件福利 编辑:程序博客网 时间:2024/04/29 05:34
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; ListNode *tempHead=head->next,*priHead=head; while(head!=NULL&&head->next!=NULL) { ListNode *temp=head->next; priHead->next=temp; head->next=temp->next; temp->next=head; priHead=head; head=head->next; } return tempHead; }};
方案二:交换结点中的值
/** * 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 *tempHead=head; while(head!=NULL&&head->next!=NULL){ int tempVal=head->val; head->val=head->next->val; head->next->val=tempVal; head=head->next->next; } return tempHead; }};
0 0
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24.Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- (OK) 编译cBPM—CentOS7—gdb—gdbserver—成功—调试
- (OK) CentOS7 中使用 QQ的方法建议——VirtualBox + WinXP
- HDU 5636:Shortest Path【Floyd】
- 屠呦呦——中国人首获诺贝尔医学奖
- sql server 日期函数datetime应用
- 24. Swap Nodes in Pairs
- Django REST 异常处理
- SQL 语句类型以及处理
- 网易2016杭研公共技术部安卓开发实习生面试
- (OK) 调试cBPM—CentOS7—gdb—gdbserver—问题的解决—1—手机死机
- 安卓POST请求+异步获取数据+JSON解析+图片解析
- java多线程-使用ReadWriteLock同步数据访问
- 使用Memory Analyzer tool(MAT)分析内存泄漏(一)
- CentOS 6 安装VMWare tools,以及解决安装后/mnt中有hgfs但没共享文件的方法