直接上代码
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//初始化单链表
void InitList(LNode **head)
{
if(head == NULL)
{
printf("head is empty");
return;
}
(*head) = NULL;
}
//尾插法建立单链表
void InsertListTail(LNode **head,int val)
{
if(head == NULL)
{
printf("head is empty!\n");
return;
}
if(*head == NULL)
{
LNode *s = (LNode*)malloc(sizeof(LNode));
if(s == NULL)
{
printf("apply fail!\n");
return;
}
s->data = val;
s->next = NULL;
*head = s;
return;
}
LNode *p = *head;
while(p->next != NULL)
{
p = p->next;
}
LNode *s = (LNode*)malloc(sizeof(LNode));
if(s == NULL)
{
printf("apply fail!\n");
return;
}
s->next = p->next;
p->next = s;
s->data = val;
}
//头插法建立单链表
void InsertListHead(LNode **head,int val)
{
if(head == NULL)
{
printf("head is empty!\n");
return;
}
LNode *p = (LNode*)malloc(sizeof(LNode));
if(p == NULL)
{
printf("apply fail!\n");
return;
}
p->data = val;
p->next = (*head);
(*head) = p;
}
//显示单链表中的信息
void ShowList(LNode **head)
{
if(head == NULL)
{
printf("head is empty!\n");
return;
}
LNode *p = (*head);
while(p != NULL)
{
printf("%d ",p->data);
p = p->next;
}
printf("\n");
}
//销毁单链表
void DestoryList(LNode **head)
{
if(head == NULL)
{
printf("head is empty!\n");
return;
}
LNode *p;
while(*head != NULL)
{
p = (*head)->next;
free(*head);
*head = p;
}
}
//头删
void DeleteListHead(LNode **head)
{
if(head == NULL)
{
printf("head is empty!\n");
return;
}
if(*head == NULL)
{
printf("单链表中无结点,无法删除!\n");
return;
}
LNode *p = *head;
LNode *q = p->next;
*head = q;
free(p);
}
//尾删
void DeleteListTail(LNode **head)
{
if(head == NULL)
{
printf("head is empty!\n");
return;
}
if(*head == NULL)
{
printf("单链表中无结点,无法删除!\n");
return;
}
LNode *p = *head;
LNode *q = p->next;
while(q->next != NULL)
{
p = q;
q = q->next;
}
p->next = NULL;
free(q);
}
//按位置删除
void ListDeletePos(LNode **head,int pos)
{
if(head == NULL)
{
printf("head is empty!\n");
return ;
}
if(*head == NULL)
{
printf("单链表中无头节点,无法删除");
return;
}
if(pos <= 0)
{
printf("删除位置不对!\n");
return;
}
LNode *p = *head;
LNode *q = p->next;
while(--pos && q->next != NULL)
{
p = q;
q = q->next;
}
*head = q;
free(p);
}
//按位置插入数据
void ListInsertPos(LNode **head,int val,int pos)
{
LNode *s = (LNode*)malloc(sizeof(LNode));
if(s == NULL)
{
printf("申请结点失败!\n");
return;
}
s->data = val;
if(head == NULL)
{
printf("head is empty!\n");
return;
}
if(pos <= 0)
{
printf("插入位置不正确,不能进行插入!\n");
return;
}
if(*head == NULL)
{
s->next = *head;
*head = s;
}
if(pos == 1)
{
LNode *c = *head;
*head = s;
s->next = c->next;
return;
}
LNode *p = *head;
LNode *q = p->next;
while((pos-2) > 0 && q != NULL)
{
p = q;
q = q->next;
--pos;
}
if(q == NULL)
{
printf("插入位置不正确,不能进行插入!\n");
return;
}
s->next = p->next;
p->next = s;
}