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;
}
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
add a comment |
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
1
if you want to remove all duplicates you can always use aset
– 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 becomehead.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
add a comment |
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
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
python
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 aset
– 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 becomehead.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
add a comment |
1
if you want to remove all duplicates you can always use aset
– 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 becomehead.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
add a comment |
2 Answers
2
active
oldest
votes
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
add a comment |
Problem Solution
- Create a class Node with instance variables data and next.
- Create a class LinkedList with instance variables head and last_node.
- The variable head points to the first element in the linked list while last_node points to the last.
- Define methods append, get_prev_node, remove and display.
- The method append takes a data item as argument and appends a node with that data item to the list.
- 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.
- The method remove takes a node as argument and removes it from the list.
- The method display traverses the list from the first node and prints the data of each node.
- Define a function remove_duplicates which takes a linked list as argument and removes duplicates from it.
- The function remove_duplicates uses two nested loops to remove duplicate nodes.
- 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
- An instance of LinkedList is created.
- The user is prompted to enter the data items for the list.
- The function remove_duplicates is called to remove duplicates from the list.
- The linked list is displayed.
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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
add a comment |
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
add a comment |
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
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
edited Jan 4 at 18:23
answered Jan 4 at 18:13
blhsingblhsing
44.9k51746
44.9k51746
add a comment |
add a comment |
Problem Solution
- Create a class Node with instance variables data and next.
- Create a class LinkedList with instance variables head and last_node.
- The variable head points to the first element in the linked list while last_node points to the last.
- Define methods append, get_prev_node, remove and display.
- The method append takes a data item as argument and appends a node with that data item to the list.
- 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.
- The method remove takes a node as argument and removes it from the list.
- The method display traverses the list from the first node and prints the data of each node.
- Define a function remove_duplicates which takes a linked list as argument and removes duplicates from it.
- The function remove_duplicates uses two nested loops to remove duplicate nodes.
- 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
- An instance of LinkedList is created.
- The user is prompted to enter the data items for the list.
- The function remove_duplicates is called to remove duplicates from the list.
- The linked list is displayed.
add a comment |
Problem Solution
- Create a class Node with instance variables data and next.
- Create a class LinkedList with instance variables head and last_node.
- The variable head points to the first element in the linked list while last_node points to the last.
- Define methods append, get_prev_node, remove and display.
- The method append takes a data item as argument and appends a node with that data item to the list.
- 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.
- The method remove takes a node as argument and removes it from the list.
- The method display traverses the list from the first node and prints the data of each node.
- Define a function remove_duplicates which takes a linked list as argument and removes duplicates from it.
- The function remove_duplicates uses two nested loops to remove duplicate nodes.
- 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
- An instance of LinkedList is created.
- The user is prompted to enter the data items for the list.
- The function remove_duplicates is called to remove duplicates from the list.
- The linked list is displayed.
add a comment |
Problem Solution
- Create a class Node with instance variables data and next.
- Create a class LinkedList with instance variables head and last_node.
- The variable head points to the first element in the linked list while last_node points to the last.
- Define methods append, get_prev_node, remove and display.
- The method append takes a data item as argument and appends a node with that data item to the list.
- 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.
- The method remove takes a node as argument and removes it from the list.
- The method display traverses the list from the first node and prints the data of each node.
- Define a function remove_duplicates which takes a linked list as argument and removes duplicates from it.
- The function remove_duplicates uses two nested loops to remove duplicate nodes.
- 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
- An instance of LinkedList is created.
- The user is prompted to enter the data items for the list.
- The function remove_duplicates is called to remove duplicates from the list.
- The linked list is displayed.
Problem Solution
- Create a class Node with instance variables data and next.
- Create a class LinkedList with instance variables head and last_node.
- The variable head points to the first element in the linked list while last_node points to the last.
- Define methods append, get_prev_node, remove and display.
- The method append takes a data item as argument and appends a node with that data item to the list.
- 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.
- The method remove takes a node as argument and removes it from the list.
- The method display traverses the list from the first node and prints the data of each node.
- Define a function remove_duplicates which takes a linked list as argument and removes duplicates from it.
- The function remove_duplicates uses two nested loops to remove duplicate nodes.
- 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
- An instance of LinkedList is created.
- The user is prompted to enter the data items for the list.
- The function remove_duplicates is called to remove duplicates from the list.
- The linked list is displayed.
answered Jan 4 at 18:23
user10866229
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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 becomehead.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