数据结构之链表(一)

来源:互联网 发布:热火队球员数据 编辑:程序博客网 时间:2024/05/22 01:35

线性表分为顺序存储结构和链式存储结构2种。

顺序存储结构的特点:任何一个元素都可以进行随即存取,存取速度高。但不适合濒繁的插入和删除操作。

链式存储结构(链表):不可以随即存取元素。但适合频繁的插入和删除操作。

一个静态链表的例子:

#include<stdio.h>
struct node
{
 int data;
 struct node *next;
};
typedef struct node nodeType;
int main()
{
 nodeType sOne,sTwo,sThree, *begin, *p;
 clrscr();
 sOne.data = 1;
 sTwo.data = 2;
 sThree.data = 3;
 begin = &sOne;
 sOne.next = &sTwo;
 sTwo.next = &sThree;
 sThree.next = '/0';
 p=begin;
 while(p)
 {
  printf("%d ",p->data);
  p=p->next;
 }
 printf("/n");
 getch();
 return 0;
}

一个动态链表的例子:

#include<stdio.h>
#include<alloc.h>
typedef struct node
{
 int data;
 struct node *next;
}nodeType;
nodeType *CreateList()     /*这个方法的作用:返回头指针(头结点),头结点没有数据域*/
{
 int i;
 nodeType *begin,*end,*current;
 begin = (nodeType *)malloc(sizeof(nodeType));
 end = begin;
/* begin->data = 1000;*/
 scanf("%d",&i);
 while(i!=-1)    /*输入为-1时,退出循环*/
 {
  current = (nodeType *)malloc(sizeof(nodeType));
  current->data = i;
  end->next = current;
  end = current;
  scanf("%d",&i);
 }
 end->next = '/0';
 return begin;
}
int main()
{
 nodeType *head;
 head = CreateList();
 while(head)
 {/* 顺序访问链表中各结点的数据域*/
  printf("%d ",head->data);   /*头结点没有数据域,所以打印头结点时,数据是随即的。 
  head=head->next;

 /* head = head->next;
  printf("%d ",head->data);
 */
 }
 getch();
 return 0;
}

实际应用中动态链表更为常用。