单循环链表
主要好处在于方便插入删除结点,适用于动态性比较强的数据结构;缺点是每一个结点只能通过上一个结点来访问,随机访问不方便。
//数据结构:单循环链表
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
typedef struct Node{
int data;
Node *next;
}Node,*PNode;//节点
typedef struct List{
PNode head;
PNode tail;
int length;
}List,*PList;//链表
void initList(PList x){
PNode headNode=(PNode)malloc(sizeof(Node));
if(!headNode)
exit(0);
headNode->data=0;
headNode->next=headNode;
x->head=headNode;
x->tail=headNode;
x->length=0;
}//初始化链表
int insertNode(PList x,int i,int e){
if(i>x->length)
return 1;
PNode newNode=(PNode)malloc(sizeof(Node));
if(!newNode)
exit(0);
newNode->data=e;
PNode p=x->head;
for(int j=0;j<i;j++)
p=p->next;
newNode->next=p->next;
p->next=newNode;
if(i==x->length)
x->tail=newNode;
x->length++;
return 0;
}//插入结点
int deleteNode(PList x,int i){
if(i>x->length)
return 1;
PNode p=x->head;
for(int j=0;j<i-1;j++)
p=p->next;
PNode delNode=p->next;
p->next=delNode->next;
if(i==x->length)
x->tail=p;
free(delNode);
x->length--;
return 0;
}//删除结点
void outputList(PList x){
PNode p=x->head->next;
for(int i=0;i<x->length;i++){
printf("%3d",p->data);
p=p->next;
}
printf("\n");
}//打印链表
int deleteList(PList x){
while(x->length>0){
deleteNode(x,x->length);
x->length--;
}
free(x->head);
x->head=NULL;
x->tail=NULL;
}//删除链表
int main(){
//初始化链表
PList myList=(PList)malloc(sizeof(List));
initList(myList);
//添加节点
int e=0;
printf("请输入要添加的数据(10个):");
for(int i=0;i<10;i++){
scanf("%d",&e);
insertNode(myList,myList->length,e);
}
outputList(myList);
//删除节点
deleteNode(myList,myList->length);
outputList(myList);
//删除链表
deleteList(myList);
return 0;
}