Given a linked list and both values V1 and v2. Swap the 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, does nothing.
Notice
You should swaps the nodes with values V1 and v2. Do not directly swap the values of the nodes.
Example
Given 1->2->3->4->null
and V1 = 2
, v2 = 4
.
Return 1->4->3->2->null
.
/*** Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int X) {val = x;}}*/ Public classSolution {/** * @paramhead a ListNode * @oaram v1 an integer *@paramv2 an integer *@returna new head of singly-linked list*/ PublicListNode Swapnodes (ListNode head,intV1,intv2) { //Write Your code here if(Head = =NULL|| Head.next = =NULL) returnHead; if(V1 = =v2)returnHead; ListNode Fakehead=NewListNode (0); Fakehead.next=Head; ListNode P1=Fakehead; ListNode P2=Fakehead; while(P1.next! =NULL){ if(P1.next.val = =v1) Break; P1=P1.next; } if(P1.next = =NULL) returnHead; while(P2.next! =NULL){ if(P2.next.val = =v2) Break; P2=P2.next; } if(P2.next = =NULL) returnHead; ListNode Node1=P1.next; P1.next=NULL; ListNode Node2=P2.next; P2.next=NULL; P2.next=Node1; P1.next=Node2; ListNode head2=NULL; ListNode head3=NULL; if(Node1.next! =NULL) head2=Node1.next; Elsehead2=NULL; if(Node2.next! =NULL) Head3=Node2.next; Elsehead3=NULL; Node2.next=head2; Node1.next=head3; returnFakehead.next; }}
Lintcode-medium-swap Nodes in Linked List