Python linked list remove duplicate





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







2















I am trying to write a code to remove duplicates from a sorted linked list "head". My code below always returns the last duplicate if the list ends with a duplicate. for e.g. [1,2,2,3,3] will return [1,2,3,3]. I can't figure out why. Does anyone have an idea?



class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""

if not head:
return head

l1=newhead=ListNode(head.val)
head=head.next


while head:
if head.val!=l1.val:
l1.next=head
l1=l1.next
head=head.next

return newhead









share|improve this question




















  • 1





    if you want to remove all duplicates you can always use a set

    – Mstaino
    Jan 4 at 17:40











  • @Mstaino can you use set operation on linked list

    – prashant rana
    Jan 4 at 17:44











  • It looks like you're missing an else in your while-loop. head should only become head.next when the values don't match, not every turn in the loop.

    – micke
    Jan 4 at 18:13











  • @micke tried still the same issue

    – Kai Sun
    Jan 4 at 18:26


















2















I am trying to write a code to remove duplicates from a sorted linked list "head". My code below always returns the last duplicate if the list ends with a duplicate. for e.g. [1,2,2,3,3] will return [1,2,3,3]. I can't figure out why. Does anyone have an idea?



class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""

if not head:
return head

l1=newhead=ListNode(head.val)
head=head.next


while head:
if head.val!=l1.val:
l1.next=head
l1=l1.next
head=head.next

return newhead









share|improve this question




















  • 1





    if you want to remove all duplicates you can always use a set

    – Mstaino
    Jan 4 at 17:40











  • @Mstaino can you use set operation on linked list

    – prashant rana
    Jan 4 at 17:44











  • It looks like you're missing an else in your while-loop. head should only become head.next when the values don't match, not every turn in the loop.

    – micke
    Jan 4 at 18:13











  • @micke tried still the same issue

    – Kai Sun
    Jan 4 at 18:26














2












2








2








I am trying to write a code to remove duplicates from a sorted linked list "head". My code below always returns the last duplicate if the list ends with a duplicate. for e.g. [1,2,2,3,3] will return [1,2,3,3]. I can't figure out why. Does anyone have an idea?



class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""

if not head:
return head

l1=newhead=ListNode(head.val)
head=head.next


while head:
if head.val!=l1.val:
l1.next=head
l1=l1.next
head=head.next

return newhead









share|improve this question
















I am trying to write a code to remove duplicates from a sorted linked list "head". My code below always returns the last duplicate if the list ends with a duplicate. for e.g. [1,2,2,3,3] will return [1,2,3,3]. I can't figure out why. Does anyone have an idea?



class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""

if not head:
return head

l1=newhead=ListNode(head.val)
head=head.next


while head:
if head.val!=l1.val:
l1.next=head
l1=l1.next
head=head.next

return newhead






python






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 4 at 17:38









jonrsharpe

79.2k11111226




79.2k11111226










asked Jan 4 at 17:37









Kai SunKai Sun

141




141








  • 1





    if you want to remove all duplicates you can always use a set

    – Mstaino
    Jan 4 at 17:40











  • @Mstaino can you use set operation on linked list

    – prashant rana
    Jan 4 at 17:44











  • It looks like you're missing an else in your while-loop. head should only become head.next when the values don't match, not every turn in the loop.

    – micke
    Jan 4 at 18:13











  • @micke tried still the same issue

    – Kai Sun
    Jan 4 at 18:26














  • 1





    if you want to remove all duplicates you can always use a set

    – Mstaino
    Jan 4 at 17:40











  • @Mstaino can you use set operation on linked list

    – prashant rana
    Jan 4 at 17:44











  • It looks like you're missing an else in your while-loop. head should only become head.next when the values don't match, not every turn in the loop.

    – micke
    Jan 4 at 18:13











  • @micke tried still the same issue

    – Kai Sun
    Jan 4 at 18:26








1




1





if you want to remove all duplicates you can always use a set

– Mstaino
Jan 4 at 17:40





if you want to remove all duplicates you can always use a set

– Mstaino
Jan 4 at 17:40













@Mstaino can you use set operation on linked list

– prashant rana
Jan 4 at 17:44





@Mstaino can you use set operation on linked list

– prashant rana
Jan 4 at 17:44













It looks like you're missing an else in your while-loop. head should only become head.next when the values don't match, not every turn in the loop.

– micke
Jan 4 at 18:13





It looks like you're missing an else in your while-loop. head should only become head.next when the values don't match, not every turn in the loop.

– micke
Jan 4 at 18:13













@micke tried still the same issue

– Kai Sun
Jan 4 at 18:26





@micke tried still the same issue

– Kai Sun
Jan 4 at 18:26












2 Answers
2






active

oldest

votes


















1














You should keep track of the leading node of each new value and keep fetching the next node until you get a node with a different value, at which point you assign that node as the next node for the leading node:



class Solution(object):
def deleteDuplicates(self, head):
node = head
while node:
lead = node
while node.next and node.next.val == lead.val:
node = node.next
node = lead.next = node.next
return head





share|improve this answer

































    0














    Problem Solution




    1. Create a class Node with instance variables data and next.

    2. Create a class LinkedList with instance variables head and last_node.

    3. The variable head points to the first element in the linked list while last_node points to the last.

    4. Define methods append, get_prev_node, remove and display.

    5. The method append takes a data item as argument and appends a node with that data item to the list.

    6. The method get_prev_node takes a reference node as argument and returns the previous node. It returns None when the reference node is the first node.

    7. The method remove takes a node as argument and removes it from the list.

    8. The method display traverses the list from the first node and prints the data of each node.

    9. Define a function remove_duplicates which takes a linked list as argument and removes duplicates from it.

    10. The function remove_duplicates uses two nested loops to remove duplicate nodes.

    11. Create an instance of LinkedList, remove duplicate nodes and display the list.


    Program/Source Code



    Here is the source code of a Python program to remove duplicates from a linked list.



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


    class LinkedList:
    def __init__(self):
    self.head = None
    self.last_node = None

    def append(self, data):
    if self.last_node is None:
    self.head = Node(data)
    self.last_node = self.head
    else:
    self.last_node.next = Node(data)
    self.last_node = self.last_node.next

    def get_prev_node(self, ref_node):
    current = self.head
    while (current and current.next != ref_node):
    current = current.next
    return current

    def remove(self, node):
    prev_node = self.get_prev_node(node)
    if prev_node is None:
    self.head = self.head.next
    else:
    prev_node.next = node.next

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


    def remove_duplicates(llist):
    current1 = llist.head
    while current1:
    data = current1.data
    current2 = current1.next
    while current2:
    if current2.data == data:
    llist.remove(current2)
    current2 = current2.next
    current1 = current1.next


    a_llist = LinkedList()

    data_list = input('Please enter the elements in the linked list: ').split()
    for data in data_list:
    a_llist.append(int(data))

    remove_duplicates(a_llist)

    print('The list with duplicates removed: ')
    a_llist.display()


    Program Explanation




    1. An instance of LinkedList is created.

    2. The user is prompted to enter the data items for the list.

    3. The function remove_duplicates is called to remove duplicates from the list.

    4. The linked list is displayed.






    share|improve this answer
























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54043644%2fpython-linked-list-remove-duplicate%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














      You should keep track of the leading node of each new value and keep fetching the next node until you get a node with a different value, at which point you assign that node as the next node for the leading node:



      class Solution(object):
      def deleteDuplicates(self, head):
      node = head
      while node:
      lead = node
      while node.next and node.next.val == lead.val:
      node = node.next
      node = lead.next = node.next
      return head





      share|improve this answer






























        1














        You should keep track of the leading node of each new value and keep fetching the next node until you get a node with a different value, at which point you assign that node as the next node for the leading node:



        class Solution(object):
        def deleteDuplicates(self, head):
        node = head
        while node:
        lead = node
        while node.next and node.next.val == lead.val:
        node = node.next
        node = lead.next = node.next
        return head





        share|improve this answer




























          1












          1








          1







          You should keep track of the leading node of each new value and keep fetching the next node until you get a node with a different value, at which point you assign that node as the next node for the leading node:



          class Solution(object):
          def deleteDuplicates(self, head):
          node = head
          while node:
          lead = node
          while node.next and node.next.val == lead.val:
          node = node.next
          node = lead.next = node.next
          return head





          share|improve this answer















          You should keep track of the leading node of each new value and keep fetching the next node until you get a node with a different value, at which point you assign that node as the next node for the leading node:



          class Solution(object):
          def deleteDuplicates(self, head):
          node = head
          while node:
          lead = node
          while node.next and node.next.val == lead.val:
          node = node.next
          node = lead.next = node.next
          return head






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jan 4 at 18:23

























          answered Jan 4 at 18:13









          blhsingblhsing

          44.9k51746




          44.9k51746

























              0














              Problem Solution




              1. Create a class Node with instance variables data and next.

              2. Create a class LinkedList with instance variables head and last_node.

              3. The variable head points to the first element in the linked list while last_node points to the last.

              4. Define methods append, get_prev_node, remove and display.

              5. The method append takes a data item as argument and appends a node with that data item to the list.

              6. The method get_prev_node takes a reference node as argument and returns the previous node. It returns None when the reference node is the first node.

              7. The method remove takes a node as argument and removes it from the list.

              8. The method display traverses the list from the first node and prints the data of each node.

              9. Define a function remove_duplicates which takes a linked list as argument and removes duplicates from it.

              10. The function remove_duplicates uses two nested loops to remove duplicate nodes.

              11. Create an instance of LinkedList, remove duplicate nodes and display the list.


              Program/Source Code



              Here is the source code of a Python program to remove duplicates from a linked list.



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


              class LinkedList:
              def __init__(self):
              self.head = None
              self.last_node = None

              def append(self, data):
              if self.last_node is None:
              self.head = Node(data)
              self.last_node = self.head
              else:
              self.last_node.next = Node(data)
              self.last_node = self.last_node.next

              def get_prev_node(self, ref_node):
              current = self.head
              while (current and current.next != ref_node):
              current = current.next
              return current

              def remove(self, node):
              prev_node = self.get_prev_node(node)
              if prev_node is None:
              self.head = self.head.next
              else:
              prev_node.next = node.next

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


              def remove_duplicates(llist):
              current1 = llist.head
              while current1:
              data = current1.data
              current2 = current1.next
              while current2:
              if current2.data == data:
              llist.remove(current2)
              current2 = current2.next
              current1 = current1.next


              a_llist = LinkedList()

              data_list = input('Please enter the elements in the linked list: ').split()
              for data in data_list:
              a_llist.append(int(data))

              remove_duplicates(a_llist)

              print('The list with duplicates removed: ')
              a_llist.display()


              Program Explanation




              1. An instance of LinkedList is created.

              2. The user is prompted to enter the data items for the list.

              3. The function remove_duplicates is called to remove duplicates from the list.

              4. The linked list is displayed.






              share|improve this answer




























                0














                Problem Solution




                1. Create a class Node with instance variables data and next.

                2. Create a class LinkedList with instance variables head and last_node.

                3. The variable head points to the first element in the linked list while last_node points to the last.

                4. Define methods append, get_prev_node, remove and display.

                5. The method append takes a data item as argument and appends a node with that data item to the list.

                6. The method get_prev_node takes a reference node as argument and returns the previous node. It returns None when the reference node is the first node.

                7. The method remove takes a node as argument and removes it from the list.

                8. The method display traverses the list from the first node and prints the data of each node.

                9. Define a function remove_duplicates which takes a linked list as argument and removes duplicates from it.

                10. The function remove_duplicates uses two nested loops to remove duplicate nodes.

                11. Create an instance of LinkedList, remove duplicate nodes and display the list.


                Program/Source Code



                Here is the source code of a Python program to remove duplicates from a linked list.



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


                class LinkedList:
                def __init__(self):
                self.head = None
                self.last_node = None

                def append(self, data):
                if self.last_node is None:
                self.head = Node(data)
                self.last_node = self.head
                else:
                self.last_node.next = Node(data)
                self.last_node = self.last_node.next

                def get_prev_node(self, ref_node):
                current = self.head
                while (current and current.next != ref_node):
                current = current.next
                return current

                def remove(self, node):
                prev_node = self.get_prev_node(node)
                if prev_node is None:
                self.head = self.head.next
                else:
                prev_node.next = node.next

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


                def remove_duplicates(llist):
                current1 = llist.head
                while current1:
                data = current1.data
                current2 = current1.next
                while current2:
                if current2.data == data:
                llist.remove(current2)
                current2 = current2.next
                current1 = current1.next


                a_llist = LinkedList()

                data_list = input('Please enter the elements in the linked list: ').split()
                for data in data_list:
                a_llist.append(int(data))

                remove_duplicates(a_llist)

                print('The list with duplicates removed: ')
                a_llist.display()


                Program Explanation




                1. An instance of LinkedList is created.

                2. The user is prompted to enter the data items for the list.

                3. The function remove_duplicates is called to remove duplicates from the list.

                4. The linked list is displayed.






                share|improve this answer


























                  0












                  0








                  0







                  Problem Solution




                  1. Create a class Node with instance variables data and next.

                  2. Create a class LinkedList with instance variables head and last_node.

                  3. The variable head points to the first element in the linked list while last_node points to the last.

                  4. Define methods append, get_prev_node, remove and display.

                  5. The method append takes a data item as argument and appends a node with that data item to the list.

                  6. The method get_prev_node takes a reference node as argument and returns the previous node. It returns None when the reference node is the first node.

                  7. The method remove takes a node as argument and removes it from the list.

                  8. The method display traverses the list from the first node and prints the data of each node.

                  9. Define a function remove_duplicates which takes a linked list as argument and removes duplicates from it.

                  10. The function remove_duplicates uses two nested loops to remove duplicate nodes.

                  11. Create an instance of LinkedList, remove duplicate nodes and display the list.


                  Program/Source Code



                  Here is the source code of a Python program to remove duplicates from a linked list.



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


                  class LinkedList:
                  def __init__(self):
                  self.head = None
                  self.last_node = None

                  def append(self, data):
                  if self.last_node is None:
                  self.head = Node(data)
                  self.last_node = self.head
                  else:
                  self.last_node.next = Node(data)
                  self.last_node = self.last_node.next

                  def get_prev_node(self, ref_node):
                  current = self.head
                  while (current and current.next != ref_node):
                  current = current.next
                  return current

                  def remove(self, node):
                  prev_node = self.get_prev_node(node)
                  if prev_node is None:
                  self.head = self.head.next
                  else:
                  prev_node.next = node.next

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


                  def remove_duplicates(llist):
                  current1 = llist.head
                  while current1:
                  data = current1.data
                  current2 = current1.next
                  while current2:
                  if current2.data == data:
                  llist.remove(current2)
                  current2 = current2.next
                  current1 = current1.next


                  a_llist = LinkedList()

                  data_list = input('Please enter the elements in the linked list: ').split()
                  for data in data_list:
                  a_llist.append(int(data))

                  remove_duplicates(a_llist)

                  print('The list with duplicates removed: ')
                  a_llist.display()


                  Program Explanation




                  1. An instance of LinkedList is created.

                  2. The user is prompted to enter the data items for the list.

                  3. The function remove_duplicates is called to remove duplicates from the list.

                  4. The linked list is displayed.






                  share|improve this answer













                  Problem Solution




                  1. Create a class Node with instance variables data and next.

                  2. Create a class LinkedList with instance variables head and last_node.

                  3. The variable head points to the first element in the linked list while last_node points to the last.

                  4. Define methods append, get_prev_node, remove and display.

                  5. The method append takes a data item as argument and appends a node with that data item to the list.

                  6. The method get_prev_node takes a reference node as argument and returns the previous node. It returns None when the reference node is the first node.

                  7. The method remove takes a node as argument and removes it from the list.

                  8. The method display traverses the list from the first node and prints the data of each node.

                  9. Define a function remove_duplicates which takes a linked list as argument and removes duplicates from it.

                  10. The function remove_duplicates uses two nested loops to remove duplicate nodes.

                  11. Create an instance of LinkedList, remove duplicate nodes and display the list.


                  Program/Source Code



                  Here is the source code of a Python program to remove duplicates from a linked list.



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


                  class LinkedList:
                  def __init__(self):
                  self.head = None
                  self.last_node = None

                  def append(self, data):
                  if self.last_node is None:
                  self.head = Node(data)
                  self.last_node = self.head
                  else:
                  self.last_node.next = Node(data)
                  self.last_node = self.last_node.next

                  def get_prev_node(self, ref_node):
                  current = self.head
                  while (current and current.next != ref_node):
                  current = current.next
                  return current

                  def remove(self, node):
                  prev_node = self.get_prev_node(node)
                  if prev_node is None:
                  self.head = self.head.next
                  else:
                  prev_node.next = node.next

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


                  def remove_duplicates(llist):
                  current1 = llist.head
                  while current1:
                  data = current1.data
                  current2 = current1.next
                  while current2:
                  if current2.data == data:
                  llist.remove(current2)
                  current2 = current2.next
                  current1 = current1.next


                  a_llist = LinkedList()

                  data_list = input('Please enter the elements in the linked list: ').split()
                  for data in data_list:
                  a_llist.append(int(data))

                  remove_duplicates(a_llist)

                  print('The list with duplicates removed: ')
                  a_llist.display()


                  Program Explanation




                  1. An instance of LinkedList is created.

                  2. The user is prompted to enter the data items for the list.

                  3. The function remove_duplicates is called to remove duplicates from the list.

                  4. The linked list is displayed.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jan 4 at 18:23







                  user10866229





































                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54043644%2fpython-linked-list-remove-duplicate%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Monofisismo

                      Angular Downloading a file using contenturl with Basic Authentication

                      Olmecas