2017-07-17 65 views
1

我已经写以下程序从链表中移除重复的,夫特链表删除重复

下面是包含节点类和方法通过遍历链接列表来删除重复的代码。

在方法removeDuplicates,但是当我表演失败而(cur != nil)检查,当改为cur.link != nil工作,但输出是不正确的。

import UIKit 

class LinkedList { 

    class Node { 
     var data:Int 
     var link: Node? 

     init(data: Int = 0){ 
      self.data = data 
      self.link = nil 
     } 
    } 

    func disp(n: Node?) -> String{ 
     var text = String() 
     var node = n 

     while node != nil{ 
      text += "\(node!.data)" 
      node = node?.link 

      if node != nil { 
       text += "--->" 
      } 
     } 

     return text 
    } 

    func removeDuplicatesNode(head : Node?) -> Node?{ 
     var cur = head 
     var prev:Node? = nil 

     let s = NSMutableSet() 

     while (cur != nil) { 

      let val:Int = cur!.data 

      if(s.contains(val)){ 
       prev?.link = cur?.link! 
      }else{ 
       s.add(val) 
       prev = cur 
      } 

      print(cur) 

      cur = cur?.link 
     } 

     return head! 
    } 

} 

var list = LinkedList() 

var removeDuplicates = LinkedList.Node(data: 1) 
removeDuplicates.link = LinkedList.Node(data: 2) 
removeDuplicates.link?.link = LinkedList.Node(data: 3) 
removeDuplicates.link?.link?.link = LinkedList.Node(data: 3) 

print("Remove Duplicates " + list.disp(n: (list.removeDuplicatesNode(head: removeDuplicates)))) 

回答

0

请检查更新的removeDuplicateNode()函数。我更新了无条件的代码。

func removeDuplicatesNode(head : Node?) -> Node?{ 
    var cur = head 
    var prev:Node? = nil 

    let s = NSMutableSet() 

    while (cur != nil) { 

     let val:Int = cur!.data 

     if(s.contains(val)){ 
      if cur?.link != nil { // Check for last Node 
       prev?.link = cur?.link! 
      }else{ 
       prev?.link = nil // If last node then assign nil value to the prev node's link 
      } 
     }else{ 
      s.add(val) 
      prev = cur 
     } 

     print(cur!) 

     cur = cur?.link 
    } 

    return head! 
} 

谢谢

+0

该工程..非常感谢你.. – Badrinath