[leetcode] 24.Swap Nodes in Pairs
2015-08-28 10:25
369 查看
题目:
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.
题意:
交换链表中每两个相邻的元素,即分成两两一组,每组前后位置交换,最后返回链表头结点。只允许使用常量的空间,不允许修改链表节点里面的值,只能交换节点的位置。
思路:
这道题目是一道基本的链表的操作的题目。链表节点位置的改变通过让它们之间的链接的顺序发生变化即可。对于某个节点位置的改变,需要改变的有两块,一是让某个前驱节点指向该节点,二是让该节点指向某个后继节点。所以我们需要保存一个前驱的节点,以及一个后继的节点。因为我们是以每两个进行分组的。我们只需要保存上一组的后面的那个节点,以及下一组的第一个节点。分别记为last与next,当前节点是两个分组的前一个节点是curr。如果这个分组只有一个节点或者没有节点了,我们就结束循环。否则需要做的是:
next = curr->next-next;//找出下一组的第一个节点。
last->next = curr->next;//让上一个节点指向本分组的第二个节点。
curr->next->next = curr;//让本分组的第二个节点指向本分组的第一个节点。
curr->next = last;//让本分组的原来的第一个节点指向下一组的第一个节点。
last = curr;//last往前推进。
curr = next;//curr往前推进。
以上。
代码如下:
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.
题意:
交换链表中每两个相邻的元素,即分成两两一组,每组前后位置交换,最后返回链表头结点。只允许使用常量的空间,不允许修改链表节点里面的值,只能交换节点的位置。
思路:
这道题目是一道基本的链表的操作的题目。链表节点位置的改变通过让它们之间的链接的顺序发生变化即可。对于某个节点位置的改变,需要改变的有两块,一是让某个前驱节点指向该节点,二是让该节点指向某个后继节点。所以我们需要保存一个前驱的节点,以及一个后继的节点。因为我们是以每两个进行分组的。我们只需要保存上一组的后面的那个节点,以及下一组的第一个节点。分别记为last与next,当前节点是两个分组的前一个节点是curr。如果这个分组只有一个节点或者没有节点了,我们就结束循环。否则需要做的是:
next = curr->next-next;//找出下一组的第一个节点。
last->next = curr->next;//让上一个节点指向本分组的第二个节点。
curr->next->next = curr;//让本分组的第二个节点指向本分组的第一个节点。
curr->next = last;//让本分组的原来的第一个节点指向下一组的第一个节点。
last = curr;//last往前推进。
curr = next;//curr往前推进。
以上。
代码如下:
/** * 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* last = NULL; ListNode* curr = head; head = head->next; while(curr != NULL && curr->next != NULL) { ListNode* next = curr->next->next; if(last != NULL) { last->next = curr->next; } curr->next->next = curr; curr->next = next; last = curr; curr = next; } return head; } };
相关文章推荐
- AngularJS+Node.js实现在线聊天室
- Node系列——Node系列中异常捕获的一个重要思考
- Node系列——Node中的异常处理。
- node.js
- HDU 4587 TWO NODES(割点,连通块,枚举)
- NodeJS优缺点及适用场景讨论
- Leetcode 222 Count Complete Tree Nodes 完全二叉树的结点数
- Merge Two Sorted Lists
- downgrade node homebrew
- 关于《Node.js 包教不包会》中cookie 与 session的补充
- Ubuntu下搭建NodeJS+Express WEB开发框架
- npm WARN uninstall not installed in /Users/hrt0kmt/node_modules: "xxx"
- Name node is in safe mode.错误处理方式 hadoop
- 导航原理实验系统软件——node-webkit初探
- nodejs实现接收Snmp的Trap消息
- NodeJs 基础知识
- Hadoop错误8_dfsadmin -report后livenodes为0 或 报错could only be replicated to 0 nodes, instead of 1
- 关于Nodejs的多进程模块Cluster
- nodejs初印象
- node schedule 使用