单链表的实现
来源:互联网 发布:数学教学软件 编辑:程序博客网 时间:2024/06/06 07:35
#include <stdio.h>#include <stdlib.h>typedef struct list{ int data; struct list *next;}List;/*function:初始化为带表头的单链表input:voidoutput:List型指针*/List *initList(void){ List *L = (List *)malloc(sizeof(List)); L->data = 0; //it means this list has o element, and is an empty list L->next = NULL; return L;}/*function:从表头插入元素input:待插入的int型数值,链表指针output:null*/void headInsert(int data, List *L){ List *newNode = (List *)malloc(sizeof(List)); newNode->data = data; newNode->next = NULL; newNode->next = L->next; L->next = newNode; L->data ++;}/*function:display the listinput:链表指针output:void*/void displayList(List *L){ List *p = L; if(L->next == NULL) { printf("This is an empty List\n"); return ; } while(p->next != NULL) { p = p->next; printf("%3d",p->data); } printf("\n");}/*function:get node at pos position and delete it from the listinput:position and listoutput:elemant with type of int*///pos = 0 means the first data not the head list, so if the list length is n,then the biggest pos is n-1int deleElem(int pos, List *L){ int i = 0; int value = 0; List *p = L, *temp = NULL; if(pos < 0 || pos >= L->data) { printf("error: Wrong pos which is not in the list\n"); exit(1); } for(i = 0; i < pos; i ++) { p = p->next; } temp = p->next; p->next = temp->next; value = temp->data; free(temp); L->data --; return value;}