【leetCode】Swap Nodes in Pairs
2015-08-01 16:06
387 查看
题目:
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.
代码:
收工~
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) { ListNode* newHead = NULL; ListNode* frontNode = NULL; ListNode* midNode = NULL; ListNode* rearNode = NULL; if (head == NULL) return NULL; //如果只有Head结点,就直接返回Head结点了 if (head->next == NULL) return head; frontNode = head->next; rearNode = head; //暂存结点,保存rearNode前面的一个node ListNode* parent = new ListNode(0); parent->next = rearNode; //如果链表只有两个结点 if (frontNode->next == NULL) { //完成两个结点的交换 rearNode->next = frontNode->next; frontNode->next = rearNode; parent->next = frontNode; return frontNode; } //如果链表有不止两个结点 while (rearNode!= NULL && frontNode != NULL) { //完成两个结点的交换 rearNode->next = frontNode->next; frontNode->next = rearNode; parent->next = frontNode; //如果head == rearNode,说明这是链表刚开始,要记录下链表头 if (head == rearNode) head = frontNode; //如果后面还存在两个(及以上)的结点,就向后移动 if (rearNode->next != NULL && rearNode->next->next != NULL) { parent = rearNode; rearNode = rearNode->next; frontNode = rearNode->next; } else break; } return head; } };
收工~
相关文章推荐
- 一棵完全二叉树,找到每个节点在这一层右边的点(Populating Next Right Pointers in Each Node)
- (easy)LeetCode 237.Delete Node in a Linked List
- win8.1 JMeter启动时显示Could not open/create prefs root node Software\JavaSoft\Prefs at root
- Node.js 使用 child_process 实现多进程
- suse10下nodejs安装时提示openssl not found的问题解决办法 1、首先确认openssl有没有安装,使用命令 openssl version 2、明明已经安装了openssl
- nodejs使用笔记
- nodejs 模块安装与使用
- MonoDevelop 常用设置和快捷键
- nodejs随记01
- nodejs安装express
- nodejs windows环境安装
- Delete Node in a Linked List Java LeetCode
- LeetCode_237 Delete Node in a Linked List
- Cannot delete .... . Name node is in safe mode
- hadoop启动后jps查看总是不显示namenode进程,然后重新格式化hdfs
- node-odata: ASP.NET WEB API OData的替代品
- VFS,super_block,inode,dentry—结构体图解
- [CareerCup] 4.2 Route between Two Nodes in Directed Graph 有向图中两点的路径
- java学习脚印:xml中空白文本结点(whitespace TextNode)处理及验证方法
- leetcode之路019 Remove Nth Node From End of List