在笔试题中经常会遇到关于链表的操作,对于我这种没有系统学过数据结构的人
来说每次写完,总会感觉有地方写的不对,所以我就完完整整地将关于链表的函数
在这来写一遍,希望再遇到这种题目的时候能手到擒来。
以下代码包含是链表的创建,插入,遍历函数。
虽然没有注释,但都在我电脑上编译通过,并且可以正常运行的。
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define ERROR 0
#define OK 1
//定义链表节点
typedef struct Node{
int data;
struct Node *next;
}Node, *pNode;
//创建一个空链表
int CreatList(pNode *pHead){
*pHead = (pNode)malloc(sizeof(Node));
(*pHead) -> next = NULL;
if(NULL == pHead)
return ERROR;
return OK;
}
//在链表的末尾插入一个节点,节点元素为e
int ListInsert_end(pNode *pHead, int e){
pNode p,s;
s = (pNode)malloc(sizeof(Node));
if(NULL == s)
return ERROR;
p = (*pHead);
while(p->next)
p = p -> next;
s -> data = e;
s -> next = NULL;
p -> next = s;
return OK;
}
//在链表的第i个节点前插入一个节点,节点元素为e
int ListInsert(pNode *pHead, int i, int e){
pNode p, s;
s = (pNode)malloc(sizeof(Node));
if(NULL == s)
return ERROR;
p = *pHead ;
while( p->next && --i){
p = p -> next;
}
if(i)
return ERROR;
s -> data = e;
s -> next = p -> next;
p -> next = s;
return OK;
}
//遍历一个链表
int ListPrint(pNode *pHead){
pNode p;
p = *pHead;
if(p->next == NULL)
{
printf("这是一个空表\n");
return OK;
}
while(p->next){
p = p -> next;
printf("%d ",p -> data);
}
printf("\n");
return OK;
}
int main(){
pNode Lc;
CreatList(&Lc);
ListInsert_end(&Lc, 1);
ListInsert_end(&Lc, 2);
ListInsert_end(&Lc, 3);
ListPrint(&Lc);
ListInsert(&Lc,2,44);
ListPrint(&Lc);
ListInsert(&Lc,4,45);
ListPrint(&Lc);
}
就这么一点代码,耗费了我好几个小时,不过收获自知,也就够了。