python列表删除重复项_从未排序的链表中删除重复项
编写一个removeduplicates()函数,该函数获取一个列表并从列表中删除所有重复的节点。列表未排序。
例如,如果链表是12->11->12->21->41->43->21,那么removeUplicates()应该将链表转换为12->11->21->41->43。
建议:请先在“实践”中解决,然后再继续解决问题。
方法1(使用两个回路)
这是使用两个循环的简单方法。外循环用于逐个选取元素,内循环将选取的元素与其余元素进行比较。
感谢Gaurav Saxena在编写此代码方面的帮助。
C++
/* Program to remove duplicates in an unsorted
linked list */
#include
using namespace std;
/* A linked list node */
struct Node
{
int data;
struct Node *next;
};
// Utility function to create a new Node
struct Node *newNode(int data)
{
Node *temp = new Node;
temp->data = data;
temp->next = NULL;
return temp;
}
/* Function to remove duplicates from a
unsorted linked list */
void removeDuplicates(struct Node *start)
{
struct Node *ptr1, *ptr2, *dup;
ptr1 = start;
/* Pick elements one by one */
while (ptr1 != NULL && ptr1->next != NULL)
{
ptr2 = ptr1;
/* Compare the picked element with rest
of the elements */
while (ptr2->next != NULL)
{
/* If duplicate then delete it */
if (ptr1->data == ptr2->next->data)
{
/* sequence of steps is important here */
dup = ptr2->next;
ptr2->next = ptr2->next->next;
delete(dup);
}
else /* This is tricky */
ptr2 = ptr2->next;
}
ptr1 = ptr1->next;
}
}
/* Function to print nodes in a given linked list */
void printList(struct Node *node)
{
while (node != NULL)
{
printf("%d
编写一个removeduplicates()函数,该函数获取一个列表并从列表中删除所有重复的节点。列表未排序。 例如,如果链表是12->11->12->21->41->43->21,那么removeUplicates()应该将链表转换为12->11->21->41->43。 建议:请先在“实践”中解决,然后再继续解决问题。 方法1(使用两个回路) 这是使用两个循环的简单方法。外循环用于逐个选取元素,内循环将选取的元素与其余元素进行比较。 感谢Gaurav Saxena在编写此代码方面的帮助。 C++ /* Program to remove duplicates in an unsorted linked list */ #include using namespace std; /* A linked list node */ struct Node { int data; struct Node *next; }; // Utility function to create a new Node struct Node *newNode(int data) { Node *temp = new Node; temp->data = data; temp->next = NULL; return temp; } /* Function to remove duplicates from a unsorted linked list */ void removeDuplicates(struct Node *start) { struct Node *ptr1, *ptr2, *dup; ptr1 = start; /* Pick elements one by one */ while (ptr1 != NULL && ptr1->next != NULL) { ptr2 = ptr1; /* Compare the picked element with rest of the elements */ while (ptr2->next != NULL) { /* If duplicate then delete it */ if (ptr1->data == ptr2->next->data) { /* sequence of steps is important here */ dup = ptr2->next; ptr2->next = ptr2->next->next; delete(dup); } else /* This is tricky */ ptr2 = ptr2->next; } ptr1 = ptr1->next; } } /* Function to print nodes in a given linked list */ void printList(struct Node *node) { while (node != NULL) { printf("%d