C和指针 十二章 双链表没有实现
程序员文章站
2024-02-29 17:27:04
...
这一章主要讲了链表;
单链表和双链表,由于某些原因,只实现了单链表;双链表等我看到后边数据结构再回来补上去
#include <stdio.h>
#include <stdlib.h>
//这段代码参考了c和指针以及深入浅出C语言程序设计链表一部分,但是插入元素的那段代码是深入浅出那里的,比较简单
typedef struct NODE
{
int value;
struct NODE *link;
} Node;
Node *head;
//使用数组建立动态链表,先创建头节点,再创建第一个数据节点,并连接到头节点后面,如果再有新数据就再创建节点
Node *creatlist( int *a, int n);
void outputlist( Node *head);//链表输出
void insertlist( Node *head, int x );//插入一个值
void deletelist( Node *head, int new_value );
int main()
{
int a[10]= { 10, 20, 30, 40, 50 }, i;
printf("数组初值是 \n");
for( i = 0; i < 5; i++ )
{
printf( "%d\t", a[i]);
}
printf("\n");
head = creatlist( a, 5 );
printf( "使用数组元素创建的动态链表:\n");
outputlist( head );
int x;
x=25;
insertlist( head, x );
deletelist( head, x );
outputlist( head );
return 0;
}
Node *creatlist( int *a, int n)
{
Node *head, *p1, *p2;
int i;
head = (Node *) malloc( sizeof( Node ) );
if( head == NULL)
{
printf("没有分配足够内存");
exit(0);
}
p1 = head;
for( i = 0; i < n; i++ )
{
p2 = malloc( sizeof( Node ) );
if( p2 == NULL)
{
printf("没有分配足够内存");
exit(0);
}
p1->link = p2;
p2->value = a[i];
p1 = p2;
}
p1->link = NULL;
return head;
}
void outputlist( Node *head)//输出链表
{
Node *p;
p = head->link;
printf("head->");
while( p != NULL )
{
printf("%d->", p->value);
p = p->link;
}
printf("NULL\n");
}
void insertlist( Node *head, int new_value )
{
Node *current;
Node *precious;
Node *news;
precious = head;
current = head->link;
while( current != NULL )
{
if( current->value < new_value )
{
precious = current;
current = current->link;
}
else
break;
}
news =(Node *) malloc( sizeof (Node) );
if (news == NULL)
{
printf("出错\n");
exit(0);
}
news->value = new_value;
news ->link = current;
precious->link = news;
outputlist( precious );
}
void deletelist( Node *head, int new_value )
{
Node *current;
Node *precious;
precious = head;
int flag;
current = head->link;
while( current != NULL )
{
if( current->value == new_value )
{
flag = 1;
break;
}
precious = current;
current = current->link;
}
if( flag == 1)
{
precious->link = current->link;
}
outputlist( precious );
}