2017-07-17 62 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