码迷,mamicode.com
首页 > 其他好文 > 详细

[GeeksForGeeks] Swap nodes in a single linked list by changing links

时间:2017-08-09 10:12:27      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:should   and   rate   sim   geek   class   blog   false   geeks   

Given a singly linked list whose nodes contain an integer as their keys. All keys are distinct. 

Swap the node that has key x with the node that has key y.  

Nothing is done if either x or y does not exist in the given linked list. 

Do this swap by changing node links, not by swaping key values.

 

Key notes:

1. Use dummy node to simply the case that either x or y is the head node.

2.  if x and y are not adjacent, then there is 4 links that need to be changed;

   if they are adjacent, then there is only 3 links that need to be changed; 

As a result, these 2 cases should be handled separately.

 

 1 class ListNode{
 2     int key;
 3     ListNode next;
 4     ListNode(int key){
 5         this.key = key;
 6         this.next = null;
 7     }
 8 }
 9 public class Solution {
10     public ListNode swapTwoNodesOfGivenKeys(ListNode head, int x, int y){
11         if(head == null || head.next == null || x == y){
12             return head;
13         }
14         ListNode dummy = new ListNode(0);
15         dummy.next = head;
16         
17         ListNode prevX = null, X = null, prevY = null, Y = null;
18         ListNode prevNode = dummy, currNode = head;
19         boolean foundX = false, foundY = false;
20         
21         while(currNode != null){
22             if(currNode.key == x){
23                 prevX = prevNode;
24                 X = currNode;
25                 foundX = true;
26             }
27             else if(currNode.key == y){
28                 prevY = prevNode;
29                 Y = currNode;
30                 foundY = true;
31             }
32             if(foundX && foundY){
33                 break;
34             }
35             prevNode = currNode;
36             currNode = currNode.next;
37         }
38         if(!foundX || !foundY){
39             return dummy.next;
40         }
41         if(X == prevY){
42             prevX.next = Y;
43             X.next = Y.next;
44             Y.next = X;
45         }
46         else if(Y == prevX){
47             prevY.next = X;
48             Y.next = X.next;
49             X.next = Y;
50         }
51         else{
52             prevX.next = Y;
53             ListNode temp = Y.next;
54             Y.next = X.next;
55             X.next = temp;
56             prevY.next = X;            
57         }
58         return dummy.next;
59     }
60 }

 

[GeeksForGeeks] Swap nodes in a single linked list by changing links

标签:should   and   rate   sim   geek   class   blog   false   geeks   

原文地址:http://www.cnblogs.com/lz87/p/7302648.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!