Swap Two Nodes in Linked List
2016-04-22 10:23
471 查看
Given a linked list and two values v1 and v2. Swap the two nodes in the linked list with values v1 and v2. It's guaranteed
there is no duplicate values in the linked list. If v1 or v2 does not exist in the given linked list, do nothing.
注意事项
You should swap the two nodes with values v1 and v2. Do not directly swap the values of the two nodes.
样例
Given
v1 =
Return
思路:
1、先创建一个新的头结点R_head,并让他指向原来的头结点,这样可以减少很多麻烦;
2、先找到v1、v2的前一个节点,由于有了第一步,无需担心v1或者v2为头结点的情况;
3、找到后交换两次,返回R_head.next。
there is no duplicate values in the linked list. If v1 or v2 does not exist in the given linked list, do nothing.
注意事项
You should swap the two nodes with values v1 and v2. Do not directly swap the values of the two nodes.
样例
Given
1->2->3->4->nulland
v1 =
2, v2 =
4.
Return
1->4->3->2->null.
思路:
1、先创建一个新的头结点R_head,并让他指向原来的头结点,这样可以减少很多麻烦;
2、先找到v1、v2的前一个节点,由于有了第一步,无需担心v1或者v2为头结点的情况;
3、找到后交换两次,返回R_head.next。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { /** * @param head a ListNode * @oaram v1 an integer * @param v2 an integer * @return a new head of singly-linked list */ public ListNode swapNodes(ListNode head, int v1, int v2) { // Write your code here ListNode pre1=null,pre2=null,now=null,R_head; R_head = new ListNode(-1); R_head.next = head; now = R_head; while(now.next!=null&&(pre1==null||pre2==null)){ if(pre1==null&&now.next.val==v1){ pre1 = now; } else if(pre2==null&&now.next.val==v2){ pre2 = now; } now = now.next; } if(pre1==null||pre2==null) return head; { now = pre1.next; pre1.next = pre2.next; pre2.next = now; now = pre1.next.next; pre1.next.next = pre2.next.next; pre2.next.next = now; } return R_head.next; } }
相关文章推荐
- NodeJs 常用工具
- RT-THREAD在IAR环境下使用finsh返回 Null node的解决办法
- node passport
- 为什么inode耗尽,而磁盘仍然有很大空间
- node.js 安装express 遇到的问题
- LeetCode之24----Swap Nodes in Pairs
- LeetCode之24----Swap Nodes in Pairs
- 用NodeJs实现延迟调用,规避定时任务的闭包问题
- 用node.js 搭建一个简单的服务器
- LintCode : Remove Node in Binary Search Tree
- How to delete a node in BST?
- nodejs中exports与module.exports的区别
- Node 之 Express 学习笔记 第一篇 安装
- 开始nodejs+express的学习+实践(1)
- 在win7系统中使用nodejs在WebStrom下配置socket.io
- Windows系统下使用Sublime搭建nodejs环境
- 222. Count Complete Tree Nodes -- 求完全二叉树节点个数
- 116. Populating Next Right Pointers in Each Node
- Node.js
- Cisco VPP(5) node关系图