#include <iostream>
#include <vector>
using namespace std;
typedef struct ListNode {
int data;
struct ListNode * next;
ListNode(int d) : data(d), next(NULL){}
};
ListNode *initList(int *array, unsigned int length) {
if(!array) {
return NULL;
}
ListNode * head = NULL;
head = new ListNode(array[0]);
ListNode * p = head;
head->next = NULL;
unsigned int i = 1;
for(; i < length; i++) {
p->next = new ListNode(array[i]);
p = p->next;
}
return head;
}
void printList(ListNode *head) {
ListNode * p = head;
if (!head){
return;
}
while (p && p->next) {
cout<<p->data<<"->";
p = p->next;
}
if (p) {
cout<<p->data<<endl;
}
}
ListNode *removeDuplicateNode(ListNode *head) {
if (head == NULL) {
return NULL;
}
ListNode *pre = head;
ListNode *post = pre->next;
while(pre != NULL && post != NULL) {
if (pre->data == post->data) {//delete post node
pre->next = post->next;
delete post;
post = pre->next;
} else {
pre = pre->next;
post = post->next;
}
}
return head;
}
int main(){
int i = 0;
int array1[9] = {1, 1, 1, 2, 2, 3, 4, 4, 5};
ListNode *head1 = NULL;
head1 = initList(array1, 9);
cout<<"list1: ";
printList(head1);
head1 = removeDuplicateNode(head1);
printList(head1);
return 1;
}
057_删除聊表中的重复的节点
最新推荐文章于 2023-06-20 18:25:24 发布