程序书海

线性表的链式存储----链表

2017-10-14  本文已影响0人  东风谷123Liter

 链表

链表是一种物理存储单元上非连续、非顺序的存储结构,它由结点组成,结点包括数据域和指针域(指向下一个地址)。它很好的解决了顺序表(数组)产生的空间资源浪费问题。

原理:每个节点的指针域内有一个指针,指向下一个节点,而最后一个节点则指向一个空值NULL,头结点一般有一个头指针head。

静态单链表:

#include<stdio.h>

// 申明结构体类型struct Student

struct Student

{

int num;

float score;

struct Student *next;

};

int main()

{

struct Student a, b, c ,*head,*p;

a.num = 1; a. score = 90;

b.num = 2; b. score = 92;

a.num = 3; a. score = 93;

// 链接起链表

head= &a;

a.next = &b;

b.next = &c;

c.next = NULL;

p = head;

// 输出链表

do       

{

printf("%d%5.1f\n",p->num,p->score);

p=p->next;

}while(p!=NULL);

return 0;

}

静态链表比较容易理解,上面结构体变量也可以式数组。

动态链表

动态链表是指一个一个的输入各结点的数据。

//动态链表的输入

int n;

struct Student *creat(void) {

struct Student *head;

struct Student *p1,*p2;

n=0;

p1=p2=(struct Student*)malloc(LEN);  ///开劈结点空间

scanf("%d,%f",&p1->num,&p1->score);

head=NULL;

while(p1->num!=0) {

n=n+1;

if(n==1) head=p1;

else p2->next=p1;

p2=p1;

p1=(struct Student*)malloc(LEN);

scanf("%d,%f",&p1->num,&p1->score);

}

p2->next=NULL;

return (head);  //返回头指针

}

上一篇 下一篇

猜你喜欢

热点阅读