今天我们来看看单链表的基本操作:初始化,插入(头插、尾插),查找,删除,判空,求长,摧毁,逆置。
.cpp:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "list.h"
void InitList(List plist)
{
assert(plist != NULL);
plist->next = NULL;
//plist->data不用操作
}
//头插
bool Insert_Head(List plist,int val)
{
Node *p = (Node *)malloc(sizeof(Node));
p->data = val;
p->next = plist->next;
plist->next = p;
return true;
}
//尾插
bool Insert_Tail(List plist,int val)
{
Node *p = (Node *)malloc(sizeof(Node));
p->data = val;
Node *q;
for(q=plist;q->next!=NULL;q=q->next) ;
//将p插入在q的后面
p->next = q->next;//p->next = NULL;
q->next = p;
return true;
}
Node *Search(List plist,int key)
{
for(Node *p=plist->next;p!=NULL;p=p->next)
{
if(p->data == key)
{
return p;
}
}
return NULL;
}
//查找key的前驱
static Node *SearchPri(List plist,int key)
{
for(Node *p=plist;p->next!=NULL;p=p->next)
{
if(p->next->data == key)
{
return p;
}
}
return NULL;
}
bool Delete(List plist,int key)
{
Node *p = SearchPri(plist,key);
if(p == NULL)
{
return false;
}
Node *q = p->next;
p->next = q->next;//将q从链表中剔除
//p->next = p->next->next;
free(q);
return true;
}
bool IsEmpty(List plist)
{
return plist->next == NULL;
}
int GetLength(List plist)
{
int count = 0;
for(Node *p=plist->next;p!=NULL;p=p->next)
{
count++;
}
return count;
}
void Show(List plist)
{
for(Node *p=plist->next;p!=NULL;p=p->next)
{
printf("%d ",p->data);
}
printf("\n");
}
void Clear(List plist)
{
Destroy(plist);
}
void Destroy(List plist)
{
Node *p;
while(plist->next != NULL)//第一种方法总删除第一个数据节点
{
p = plist->next;
plist->next = p->next;
free(p);
}
/*
Node *p = plist->next;//第二种方法
//Node *q = p->next;//bug
Node *q;
while(p != NULL)
{
q = p->next;
free(p);
p = q;
}
plist->next = NULL;
*/
}
void Revers(List plist)//逆置
{
//第一种方法头插的思想
if(plist==NULL || plist->next==NULL ||
plist->next->next==NULL)
{
return ;
}
Node *p = plist->next;
Node *q;
plist->next = NULL;//
while(p != NULL)
{
q = p->next;
//将p头插进链表
p->next = plist->next;
plist->next = p;
p = q;
}
//第二种方法
#if 0
/*if(plist->next->next==NULL ||
plist==NULL || plist->next==NULL
)*///error
if(plist==NULL || plist->next==NULL ||
plist->next->next==NULL)
{
return ;
}
Node*p = plist->next;
Node *q = p->next;
Node *s;
p->next = NULL;
while(q != NULL)
{
s = q->next;
q->next = p;
p = q;
q = s;
}
plist->next = p;
#endif
}
.h:
#pragma once
//带头节点的单链表
typedef struct Node
{
int data;//数据域
struct Node *next;//指向下一个节点
}Node,*List;//List == Node*
void InitList(List plist);//Node *plist
//头插
bool Insert_Head(List plist,int val);
//尾插
bool Insert_Tail(List plist,int val);
Node *Search(List plist,int key);//List
Node *Search_before(List plist,int key);
bool Delete(List plist,int key);
bool IsEmpty(List plist);
int GetLength(List plist);
void Show(List plist);
void Clear(List plist);
void Destroy(List plist);
void Revers(List plist);