描述
给你一个链表以及两个权值v1和v2,交换链表中权值为v1和v2的这两个节点。保证链表中节点权值各不相同,如果没有找到对应节点,那么什么也不用做。
你需要交换两个节点而不是改变节点的权值
样例
给出链表 1->2->3->4->null ,以及 v1 = 2 , v2 = 4
返回结果 1->4->3->2->null。
代码
根据给定的两个值,交换两个节点,有两种情况(在两个节点能找到的情况下),一种是两个相邻,另一种是不相邻。
/**
* Definition for ListNode
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/**
* @param head: a ListNode
* @param 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
if(head==null){
return null;
}
ListNode node=new ListNode(1);
node.next=head;
ListNode cur=head,pre1=null,pre2=null,pre=node;
while(cur!=null){
if(cur.val==v1||cur.val==v2){
if(pre1==null){
pre1=pre;
}else if(pre2==null){
pre2=pre;
break;
}
}
pre=cur;
cur=cur.next;
}
if(pre1==null||pre2==null){
node.next=null;//help gc
return head;
}
if(pre1.next==pre2){ //相邻的情况
ListNode node2=pre2.next;
pre1.next=node2;
pre2.next=node2.next;
node2.next=pre2;
}else{ //不相邻的情况
ListNode node1=pre1.next,node2=pre2.next;
ListNode next1=node1.next;
ListNode next2=node2.next;
pre1.next=node2;
node2.next=next1;
node1.next=next2;
pre2.next=node1;
}
return node.next;
}
}