关于单链表的操作中,关系到头节点创建和更改的要用二级指针或者一级指针引用,其他的可用一级指针
#pragma once
#include<iostream>
#include<assert.h>
using namespace std;
typedef struct ListNode
{
int data;
struct ListNode* next;
}Node;
void PrintList(Node* head);
Node* BuyNode(int x);//创造新节点
void PushBack(Node* &head,int x);
void PushFront(Node* &head,int x);
void PopBack(Node* &head);
void PopFront(Node* &head);
Node* Find(Node* head,int x);
void Destory(Node* &head);//清空链表
void Insert(Node* &head, Node* pos, int x);
void Erase(Node* &head, Node* pos);
//输出链表
void PrintList(Node* head)
{
if (NULL == head)
{
cout << "空链表"<<endl;
return;
}
Node* cur = head;
while (cur)
{
cout << cur->data << "->";
cur = cur->next;
}
cout << "NULL" << endl;
}
//创造新节点
Node* BuyNode(int x)
{
Node* cur = (Node*)malloc(sizeof(Node));
cur->data = x;
cur->next = NULL;
return cur;
}
//尾插
void PushBack(Node* &head, int x)
{//空 或者 不空
if (NULL == head)
{
head = BuyNode(x);
}
else
{
Node* cur = head;
while (cur->next)
{
cur = cur->next;
}
cur->next = BuyNode(x);
}
}
//头插
void PushFront(Node* &head, int x)
{//空 或者 不空
if (NULL == head)
head = BuyNode(x);
else
{
Node* cur = BuyNode(x);
cur->next = head;
head = cur;
}
}
//尾删
void PopBack(Node* &head)
{
if (NULL == head) //空
return;
else if (NULL == head->next)//一个
{
free(head);
head = NULL;
}
else
{
Node* cur = head; //多个
while (cur->next->next)
{
cur = cur->next;
}free(cur->next);
cur->next = NULL;
}
}
//头删
void PopFront(Node* &head)
{
if (NULL == head) //空的
return;
else if (head->next==NULL) //一个
{
free(head);
head = NULL;
}
else
{
Node* cur = head->next;//多个
free(head);
head = cur;
}
}
Node* Find(Node* head,int x)
{
while (head)
{
if (head->data == x)
return head;
else
head = head->next;
}
return NULL;
}
//清空链表
void Destory(Node* &head)
{
if (head == NULL)
return;
Node* cur = head;
while (cur)
{
Node* next = cur->next;
free(cur);
cur = next;
}
head = NULL;
}
//在pos前面插入元素x
void Insert(Node* &head, Node* pos, int x)
{
assert(head);
assert(pos);
if (head == pos)
PushFront(head,x);
else
{
Node* cur=head;
while (cur->next!=pos)
{
cur = cur->next;
}
Node* newNode = BuyNode(x);
newNode->next = cur->next;
cur->next = newNode;
}
}
//指定位置删除
void Erase(Node* &head, Node* pos)
{
assert(head);
assert(pos);
if (pos == head)
PopFront(head);
else
{
Node* cur = head;
while (cur->next != pos)
{
cur = cur->next;
}
cur->next = pos->next;
free(pos);
pos = NULL;
}
}
int main()
{
Node* list = NULL;
PushBack(list, 2);
PushBack(list, 3);
PushBack(list, 5);
PushBack(list, 6);
PushFront(list, 1);
PushFront(list, 0);
PrintList(list);
PopBack(list);
PopFront(list);
PrintList(list);
Node* pos1=Find(list,5);
Insert(list, pos1, 4); PrintList(list);
Node* pos2 = Find(list, 3);
Erase(list,pos2);
PrintList(list);
Destory(list);
PrintList(list);
system("pause");
return 0;
}