“ if”和“ while循环”之间有什么区别?

时间:2019-07-26 01:15:22

标签: python python-3.x algorithm

我有关于链表的代码。现在,我想使用removeDuplicates()函数删除其中的重复项,并且在执行此操作时,我对'if statements'和'while loop'之间的区别存在疑问:

class Node:
    def __init__(self,data):
        self.data = data
        self.next = None
class Solution:
    def insert(self,head,data):
            p = Node(data)
            if head==None:
                head=p
            elif head.next==None:
                head.next=p
            else:
                start=head
                while(start.next!=None):
                    start=start.next
                start.next=p
            return head
    def display(self,head):
        current = head
        while current:
            print(current.data,end=' ')
            current = current.next

    def removeDuplicates(self,head):
        new_node = Node(data)
        if head == None:
            return None
        else:
            current = head
            while current.next:
                while current.data == current.next.data:
                    current.next = current.next.next
                current = current.next
            return head

mylist= Solution()
T=int(input())
head=None
for i in range(T):
    data=int(input())
    head=mylist.insert(head,data)
head=mylist.removeDuplicates(head)
mylist.display(head); 
# Here is the input: 6: 1 1 1 1 1 1 

我希望输出为1,但是会引发错误:

  

while current.data == current.next.data:

     
    

AttributeError:“ NoneType”对象没有属性“ data”。

  

但是在这段代码中:

while current.data == current.next.data

我将其更改为:

if current.data == current.next.data

它有效。你能解释一下吗?

0 个答案:

没有答案