24. Swap Nodes in Pairs
2016-04-05 00:31
585 查看
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) return head; ListNode *p=head, *q=NULL, *r=head; if (p) q = head->next; if (p && q){ p->next = q->next; q->next = p; head = q; } r = p; p = p->next; q = NULL; if (p) q = p->next; while (p && q){ p->next = q->next; q->next = p; r->next = q; r = p; p = p->next; q = NULL; if (p) q = p->next; } return head; } };
相关文章推荐
- Nodejs积累
- Nodejs超方便更新方式
- (四)Electron 把boostrap控件当做桌面控件用
- 使用nvm让不同版本的Node.js共存
- ECMAScript 2015 (ES6) in Node.js(译)
- nodejs群聊和私聊
- 24. Swap Nodes in Pairs
- Node.js其他模块
- 深入浅出NodeJS笔记(五)---- Promise的序列执行
- 基于NodeJS的秘室聊天室
- LeetCode-24.Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- nodejs的安装及从测试
- Sublime Es6教程2-基本语法
- Sublime Es6教程1-环境搭建
- Nodejs之request 和 response 对象的具体介绍
- LeetCode 222. Count Complete Tree Nodes(完全二叉树节点数统计)
- 理解inode
- Nodejs之文件系统的使用
- Node 重启服务器的 几种常用方法