SlinkList(不帶頭節點的單鏈表)20171003

#include
typedef int Datatype;
typedef struct link_node {
Datatype info;
struct link_node *next;
}node;


node *init(node *head)
{
return NULL;
}


void display(node *head)
{
if (!head)
printf("鏈表爲空,無法進行輸出!\n");
else
{
node *p = head;
while (p)
{
printf("%5d", p->info);
p = p->next;
}
}
}


node *find(node *head, int i)
{
node *p = head;
int j = 2;;
if (i == 1)
return head;
else
{
p = p->next;
while (p&&i != j)
{
p = p->next;
++j;
}
if (!p&&i != j)
{
printf("沒有找到第%d個結點\n", i);
return NULL;
}
else
if(i==j)
return p;
}
}


node *insert(node *head, Datatype x, int i)
{
node *p;
node *q=(node *)malloc(sizeof(node));
q->info = x;
q->next = NULL;
if (i == 0)
{
q->next = head;
head = q;
}
else
{
p = find(head, i);
if (p)
{
q->next = p->next;
p->next = q;
}
}
return head;
}


node *find_last(node *head)
{
node *pre = init(&pre), *p=head;
while (p)
{
pre = p;
p = p->next;
}
return pre;
}


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


node *dele(node *head, Datatype x)
{
node *p = head,*pre=init(&pre);
if (!p)
printf("鏈表爲空,無法進行刪除!\n");
else
{
while (p&&p->info != x)
{
pre = p;
p = p->next;
}
if (!p&&p->info != x)
printf("沒有找到要刪除的值!\n");
else
if (p->info == x)
pre->next = p->next;
}
return head;
}


void main()
{
node *head;
head = init(&head);
int i;
node *f;
for(i=0;i<10;i++)
head = build(head, i*2);
display(head);
putchar('\n');
f = find(head, 8);
printf("第8個結點的值爲:%d\n", f->info);
head = insert(head, 666, 8);
printf("在第8個結點後插入一個值後鏈表爲:");
display(head);
putchar('\n');
head = dele(head, 8);
printf("刪除值爲8的結點後鏈表爲:");
display(head);
putchar('\n');
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章