LeetCode--24. Swap Nodes in Pairs
2016-03-23 22:30
567 查看
Problem:
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.
Analysis:
题目意思:
给定一个链表,调换每两个相邻节点,并返回其头部。
例如, 给定 1->2->3->4, 你应该返回的链表是 2->1->4->3。
你的算法必须使用唯一不变的空间。
你也不能修改列表中的值,只有节点本身是可以改变的。
链表问题,这个题需要多用一个节点,一个标记一对中的第一个,一个标记一对中的第二个。
Answer:
经验:
1.一般链表的问题如果会返回链表(从头开始)则最好用以下的三行代码,helper来记住链表开头,p来进行运算;而且p = helper后p和helper指向的下一个节点一致。
2.p = p.next这句语句就是将p的指针后移(因为是对p操作的),p.next = t2这句与句就是把p的指向变换(因为是对p.next操作的),
p.next.next = p就是对p的下一个节点的指向操作。
3.while(p.next != null && p.next.next != null)这句语句来进行下一个节点是否满足情况的分析。
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.
Analysis:
题目意思:
给定一个链表,调换每两个相邻节点,并返回其头部。
例如, 给定 1->2->3->4, 你应该返回的链表是 2->1->4->3。
你的算法必须使用唯一不变的空间。
你也不能修改列表中的值,只有节点本身是可以改变的。
链表问题,这个题需要多用一个节点,一个标记一对中的第一个,一个标记一对中的第二个。
Answer:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode swapPairs(ListNode head) { if(head==null || head.next==null) return head; ListNode pre=new ListNode(0); pre.next= head; ListNode p=pre; while(p.next!=null && p.next.next!=null){ // ListNode t1 = p; p=p.next; t1.next=p.next; // ListNode t2 = p.next; p.next.next =p; p.next=t2; } return pre.next; } }
经验:
1.一般链表的问题如果会返回链表(从头开始)则最好用以下的三行代码,helper来记住链表开头,p来进行运算;而且p = helper后p和helper指向的下一个节点一致。
ListNode helper = new ListNode(0); helper.next = head; ListNode p = helper;
2.p = p.next这句语句就是将p的指针后移(因为是对p操作的),p.next = t2这句与句就是把p的指向变换(因为是对p.next操作的),
p.next.next = p就是对p的下一个节点的指向操作。
3.while(p.next != null && p.next.next != null)这句语句来进行下一个节点是否满足情况的分析。
相关文章推荐
- leetcode——237——Delete Node in a Linked List
- 从原型链看DOM--Node类型
- leetcode 25. Reverse Nodes in k-Group
- Inode详解
- Reverse Nodes in k-Group
- Nodejs学习笔记(十四)— Mongoose介绍和入门
- Windows下Node.js安装教程
- 使用Node.js+Socket.IO搭建WebSocket实时应用
- NodeJs 发送request请求 设置Cookie
- 25. Reverse Nodes in k-Group
- node js官网下载地址
- nodejs 异步协同问题
- gulp教程之gulp中文API
- gulp详细入门教程
- Node.js 的适用及不适用场合
- 'UserInfoBLL' node cannot be resolved for the specified context [MVC展示数据.Controllers.LoginController]问题解决
- Hadoop SecondaryNameNode
- meteor安装过慢 curl install.meteor.com | sh
- Win7下安装Node + WebMatrix
- [leetcode 24]Swap Nodes in Pairs-----成对翻转链表中的节点