单链表的基础操作 包括: 查找、插入、删除、创建链表等。
以下直接用程序进行说明:
#include<stdlib.h> // malloc free 头文件
#include <stdio.h>
// 节点定义
typedef struct Node
{
int data;
struct Node *next;
}Node;
// 查找第一个值为X的节点
Node *Serach(Node *pHead,int x)
{
Node *p=pHead;
while(p!=NULL && p->data!=x)
p=p->next;
return p;
}
// 在p节点之后进行插入
void Insert(Node *p,int x)
{
Node *s;
s=(Node*)malloc(sizeof(Node));
s->data=x;
s->next=p->next;
p->next=s;
}
// 删除 p->next节点
void DeleteFollowNode(Node *p)
{
Node *q;
q=p->next;
if(q!=NULL)
{
p->next=q->next;
free(q);
}
}
// 删除 p节点
void Delete(Node *p,Node *pHead)
{
if (p==NULL)
return;
Node *qPre=pHead;
while(qPre!=NULL&&qPre->next!=p)
qPre=qPre->next;
if (qPre!=NULL&&p!=NULL)
{
qPre->next=p->next;
free(p);
}
}
// 创建链表, 新节点在插入到最前面
Node* CreateListAhead(int a[],int n)
{
Node *s,*pHead;
int i;
pHead=(Node*)malloc(sizeof(Node));
pHead->data=0;
pHead->next=NULL;
// 新节点 在最前面进行插入
for(i=n-1;i>=0;i--)
{
s=(Node*)malloc(sizeof(Node));
s->data=a[i];
s->next=pHead->next;
pHead->next=s;
}
return pHead;
}
// 创建链表, 新节点在插入到末尾
Node* CreateListTail(int a[],int n)
{
Node *s,*pHead,*pTail;
int i;
pHead=(Node*)malloc(sizeof(Node));
pHead->data=0;
pHead->next=NULL;
pTail=pHead;
// 新节点 插入到末尾
for(i=0;i<n;i++)
{
s=(Node*)malloc(sizeof(Node));
s->data=a[i];
s->next=NULL;
pTail->next=s;
pTail=s;
}
return pHead;
}
//遍历链表
void Print(Node *h)
{
Node *p;
p=h->next;
while(p!=NULL)
{
printf("%d,",p->data);
p=p->next;
}
printf("\n");
}
//应用实例
void main()
{
int a[]={3,2,1,4,5};
Node *pHead,*p;
pHead=CreateListTail(a,5);
Print(pHead);
p=Serach(pHead,4);
printf("%d\n",p->data);
p=pHead->next->next;
Insert(p,9);
Print(pHead);
p=pHead->next->next->next;
Delete(p,pHead);
Print(pHead);
while(getchar()!='a')
;
}