swap nodes in pairs
2016-04-07 23:14
561 查看
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given1->2->3->4, you should return the list as2->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.
For example,
Given1->2->3->4, you should return the list as2->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.
class Solution { public: ListNode* swapPairs(ListNode* head) { if (head == NULL || head->next == NULL) return head; ListNode dummy(-1); dummy.next = head; ListNode* pre = &dummy; int tmp = 0; for(ListNode* before = head, *after = head->next; after; ) { tmp = before->val; before->val = after->val; after->val = tmp; before = before->next ? before->next->next : NULL; after = after->next ? after->next->next : NULL; } return dummy.next; } };
相关文章推荐
- LeetCodet题解--19. Remove Nth Node From End of List(删除链表的倒数第n个元素)
- FILE 结构体的定义,inode ,软链接和硬链接的理解
- #leetcode#237. Delete Node in a Linked List
- [置顶] windows上node-webkit安装sqlite、socket的那些坑
- 简单理解 unix (liunx)inode
- 关于childNodes及children的区别(图文结合)
- node使用buffer生成图片
- DataNode本地数据存储和管理--ncp_block_verification.log.curr和dncp_block_verification.log.prev
- inode 及软链接、硬链接
- hadoop SecondNamenode
- node.js第一步
- Hadoop集群所有的DataNode都启动不了解决办法
- Namenode HA原理详解(脑裂)
- win系统下nodejs安装及环境配置
- inode及硬链接和软链接
- Node.js简单介绍
- inode 、软(硬)链接及fork与vfork
- nodejs小记之jqueryfileupload异步图片文件上传 带上传进度
- node.js系统找不到指定文件报错
- nw.js node-webkit系列(20)拖动文件到页面并读取文件信息