iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 25
0
Software Development

30 天把自己榨好榨滿的四週四語言大挑戰!系列 第 25

[Day 24] 一條獨一無二的鏈

今天在 Hackerrank 的主題是,延續我們之前研究的 Linked list,為這個 Linked list 去增加一個 Function 來把 Linked list 中重複值的節點給移除掉。為了簡單起見,這裡重複的值必須是連續的,例如 1 2 2 3 3 會變成 1 2 3,但 1 3 1 3 還是一樣 1 3 1 3。那就讓我們開始吧!(其實不是很懂 Hackerrank 為什麼要出這題,哈哈哈!)


Python

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None 

def display(head):
  current = head
  while current:
    print(current.data, end=' ')
    current = current.next

def insert(head, data): 
  node = Node(data)
  if head is None:
    head = node
  else:
    current = head
    while(current.next is not None):
      current = current.next
    current.next = node
  return head

def remove_duplicates(head):
  curr = head
  while curr is not None and curr.next is not None:
    while curr.next is not None and curr.data is curr.next.data:
      curr.next = curr.next.next
    curr = curr.next
  return head  

time = int(input())
head = None
for i in range(time):
    data = int(input())
    head = insert(head, data)  
remove_duplicates(head)   
display(head)
  • 這裡我們加上一個新的 Function remove_duplicates,概念上就是當找到相鄰若是相同的,那就忽略掉重複的 Node,讓目前的 Nodecurr) 的 next 略過本來的下一個 Node 去指到下下個 Node,假設還是重複就繼續下去直到不重複為止。相信看上述程式的部分應該不難懂囉!

上一篇
[Day 23] 再好好看看這棵樹
下一篇
[Day 25] 與時間複雜度的競賽
系列文
30 天把自己榨好榨滿的四週四語言大挑戰!30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言