#include <stdio.h>
#include <stdlib.h>
typedef struct list
{
int data;
struct list *next;
}List;
/*
function:初始化为带表头的单链表
input:void
output: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 list
input:链表指针
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 list
input:position and list
output: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-1
int 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;
}
单链表的实现
最新推荐文章于 2024-10-16 10:35:43 发布