您的位置:首页 > Web前端 > Node.js

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
1->2->3->4->null
and
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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: