C语言单链表
1、单链表定义
链表是通过一组任意的存储单元来存储线性表中的数据元素,这些存储单元可以是连续的也可以是不连续的。为了建立起数据元素之间的关系,对于每个数据元素除了存放数据元素自身的信息外,还必须有包含的指示该元素直接后继元素存储位置的信息,这两部分信息组成一个结点,即每个结点都有至少包括两个域,一个域存储数据元素信息,称为数据域,另一个域存储直接后继的地址,称为指针域。那么顾名思义,单链表即每个结点只有一个指针域。
单链表又有带头结点和不带头结点的单链表
带头结点的单链表,头指针head指向头结点,头结点的值域不包含任何信息,从头结点之后的结点开始存储信息。看个人编程习惯决定使用哪一种单链表。
2、头插法建单链表
下面用代码完成:用头插法将“I love program”放至链表中,并输出验证结果。
#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX 14
struct list
{
char string;
struct list *next;
};
typedef struct list node;
typedef node *link;
char string[MAX]={'I',' ','l','o','v','e',' ','p','r','o','g','r','a','m'};
link create_list(link head)
{
link newpointer;
char ch;
int i;
head=(link)malloc(sizeof(node));
if(head==NULL)
printf("exit\n");
else
{
head->string=string[0];
head->next=NULL;
for(i=1;i<MAX;i++)
{
newpointer=(link)malloc(sizeof(node));
if(newpointer==NULL)
printf("exit\n");
else
{
newpointer->string=string[i];
newpointer->next=head;
head=newpointer;
}
}
}
return head;
}
void printf_list(link head)
{
link temp;
temp=head;
while(temp!=NULL)
{
printf("%c",temp->string);
temp=temp->next;
}
}
void free_list(link head)
{
link temp;
while(head!=NULL)
{
temp=head;
head=head->next;
free(temp);
}
}
int main()
{
link head;
head = create_list(head);
if(head!=NULL)
{
printf_list(head);
free_list(head);
}
printf("\n");
return 0;
}
3、尾插法建单链表
下面用代码完成:用尾插法将“I love program”放至链表中,并输出验证结果。
#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX 14
struct list
{
char string;
struct list *next;
};
typedef struct list node;
typedef node* link;
char string[MAX]={'I',' ','l','o','v','e',' ','p','r','o','g','r','a','m'};
link create_list(link head)
{
link pointer,newpointer;
int i;
head=(link)malloc(sizeof(node));
if(head==NULL)
printf("exit\n");
else
{
head->string=string[0];
head->next=NULL;
pointer=head;
for(i=1;i<MAX;i++)
{
newpointer=(link)malloc(sizeof(node));
if(newpointer==NULL)
printf("exit\n");
else
{
newpointer->string=string[i];
newpointer->next=NULL;
pointer->next=newpointer;
pointer=newpointer;
}
}
}
return head;
}
void printf_list(link head)
{
link temp;
temp=head;
while(temp!=NULL)
{
printf("%c",temp->string);
temp=temp->next;
}
}
void free_list(link head)
{
link temp;
while(head!=NULL)
{
temp=head;
head=head->next;
free(temp);
}
}
int main()
{
link head;
head=create_list(head);
if(head!=NULL)
{
printf_list(head);
free_list(head);
}
printf("\n");
return 0;
}
本文参考博文:
C语言单链表基本操作总结
单链表
CSDN字体格式(字体、颜色、大小)、背景色设置