1、头文件
#ifndef _83
#define _83
#include <iostream>
using namespace std;
struct ListNode{
int val;
ListNode *next;
/*ListNode(int x) :val(x), next(NULL){}*/
};
void initList(ListNode *L); //初始化链表
ListNode *createListTail(); //创建链表(尾插法)
ListNode *createListHead(); //创建链表(头插法)
void displayList(ListNode *L);//打印链表
void deleteList(ListNode *&L,int value);//删除链表元素
ListNode* deleteDuplicates(ListNode* head);//删除重复元素
#endif
2、功能实现(cpp)
#include "83.h"
void initList(ListNode *L){
L = nullptr;
}
ListNode *createListHead()
{
ListNode *head = new ListNode;
if (head == nullptr) {
cout << "分配内存失败";
}
head->next = nullptr;
int nodeValue;
while (cin >> nodeValue && nodeValue != -1){
ListNode *temp = new ListNode;
temp->val = nodeValue;
temp->next = head->next;
head->next = temp;
}
return head;
}
ListNode *createListTail()
{
ListNode *head = new ListNode;
if (head == nullptr) {
cout << "分配内存失败";
}
head->next = nullptr;
ListNode *tail = head;
int nodeValue;
while (cin >> nodeValue && nodeValue != -1){
ListNode *temp = new ListNode;
temp->val = nodeValue;
tail->next = temp ;
tail = temp;
}
tail->next = nullptr;
return head;
}
void deleteList(ListNode *&L,int value)
{
ListNode *head =L;
ListNode *p;
while (head && head->next){
if (head->next->val == value)
{
p = head->next;
head->next = head->next->next;
}
else
{
head = head->next;
}
}
}
ListNode* deleteDuplicates(ListNode* head)
{
ListNode *pre = head;
while (pre->next && pre)
{
if (pre->next->val == pre->val)
{
pre->next= pre->next->next;
}
else
pre = pre->next;
}
return head;
}
void displayList(ListNode *L){
while (L->next&&L)
{
cout << L->next->val << "->";
L = L->next;
}
cout << "null" << endl;
}
3、主函数(main.cpp)
#include "83.h"
int main(){
ListNode *L = new ListNode;
initList(L);
L = createListTail();
displayList(L);
//deleteList(L,1);
//displayList(L);
deleteDuplicates(L);
system("pause");
return 0;
}