slnklist(不带头结点的单链表)

来源:互联网 发布:淘宝客服培训班 编辑:程序博客网 时间:2024/05/18 01:34
#include<stdio.h>
typedef int datatype;


typedef struct link_node {
datatype info;
struct link_node *next;
}node;


node *init()
{
return NULL;
}


void display(node *head)
{
node *p;
p = head;
if (!p)
printf("单链表是空的!");
else
{
printf("依次输出:\n");
while (p)
{
printf("%d\t", p->info);
p = p->next;
}
}
printf("\n");
}


node *find(node *head, int i)
{
int j = 1;
node *p = head;
if (i == 0)
return head;
while (p&&i != j)
{
p = p->next;
j++;
};
if (i != j)
return NULL;
return p;
}


node *insert(node *head, datatype x, int i)
{
node *p, *q;
q = find(head, i);
if (!q)
{
printf("找不到要插入的位置!\n");
}
else
{
p = (node *)malloc(sizeof(node));
p->info = x;
if (i == 0)
{
p->next = head;
head = p;
}
else
{
p->next = q->next;
q->next = p;
}
}
return head;
}


node *find_last(node *head)
{
node *p,*pre;
if (!head)
printf("表是空的!\n");
else
{
p = head;
while (p)
{
pre = p;
p = p->next;
}
return pre;
}
}


node *build(node *head, datatype x)
{
node *q = (node *)malloc(sizeof(node));
q->info = x;
q->next = NULL;
if (!head)
{
head = q;
}
else
{
node *p = find_last(head);
p->next = q;
}
return head;
}


node *dele(node *head, datatype x)
{
node *pre, *p;
if (!head)
printf("表是空的!\n");
else
{
p = head;
if (head->info == x)
{
head = p->next;
free(p);
}
while (p&&p->info != x)
{
pre = p;
p = p->next;
}
if (!p&&pre->info != x)
{
printf("没有找到要删的节点!\n");
}
else
{
pre->next = p->next;
free(p);
}
}
return head;
}


void main()
{
node *N,*head;
head = init();
int i = 0; 
for (i = 0; i < 10; i++)
head = build(head, i * 3);
display(head);
N = find(head, 3);
printf("%d\n", N->info);
head = insert(head, 100, 2);
display(head);
head = insert(head, 200, 0);
display(head);
head = dele(head, 15);
display(head);
}