24. Swap Nodes in Pairs
2016-03-30 15:53
369 查看
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
我的答案:
方案一:交换结点
方案二:交换结点中的值
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; } };
相关文章推荐
- 92. Reverse Linked List II
- 237. Delete Node in a Linked List
- Node.js中,q在链式调用和异步调用中起到的作用
- Windows 10 下安装 npm 后全局 node_modules 和 npm-cache 文件夹的设置
- 作用域与闭包
- Node
- 【转】如何使用NPM来管理你的Node.js依赖
- nodejs在线xlsx转json
- NodeJS 回调函数中的this
- Node.js学习
- file_operations -- file -- inode
- H5+MUI+Node.js+Socket.io群组即时聊天+发送图片+图片压缩
- H5+MUI+Node.js+Socket.io实现即时聊天以及发送+图片压缩
- Node.js升级最新版本
- nodeJs学习路线
- LeetCode 19 Remove Nth Node From End of List
- File-nodejs
- iOS GDataXMLNode的配置步骤
- 24.LeetCode Swap Nodes in Pairs(easy)[单链表]
- leetcode之delete Node in a Linked List