2008秋季-计算机软件基础-0908课堂用例(2)

本文介绍了使用C语言实现链表的基本操作,包括初始化链表、在链表头部和尾部添加元素,以及打印链表内容的方法。通过具体示例展示了如何创建一个包含三个整数节点的链表。
#include < stdio.h >
#include
< stdlib.h >
struct  nodetype
{
    
int  data;
    
/*  data数据项用于存放结点的数据值  */
    
struct  nodetype  * next; 
    
/*  next数据项存放下一个结点的指针  */
};
struct  nodetype  *  InitialLinkList ()
{
 
struct  nodetype  *  head;
 head
= ( struct  nodetype  * )malloc( sizeof ( struct  nodetype )); //
 head -> next = NULL;
 
return  head;
}

void  CreateLinkListInRear( struct  nodetype  *  head,  int  a[],  int  n)
{   
int  i;   struct  nodetype  *  temp, *  rear;
    rear
= head;
    
for (i = 0 ;i < n;i ++ )
    {
        temp
= ( struct  nodetype  * )malloc( sizeof ( struct  nodetype));
        temp
-> data = a[i];
        temp
-> next = NULL;
        rear
-> next = temp;
    rear
= temp;
    }
}

void  CreateLinkListInHead( struct  nodetype  *  head,
                          
int  a[],  int  n)
{   
int  i; struct  nodetype  *  temp, * front;
    
for (i = 0 ;i < n;i ++ )
    {
        temp
= ( struct  nodetype  * )malloc(
            
sizeof ( struct  nodetype));
        temp
-> data = a[i];
        temp
-> next = head -> next;
        head
-> next = temp;
    }
}

void  printlinklist( struct  nodetype  *  head)
{
  
struct  nodetype  *  p;
  p
= head -> next;
  
while (p != NULL)
  {
    printf(
"  %d  " ,p -> data);
    p
= p -> next;
  }
}

void  main()
{
  
struct  nodetype  *  head;
  
int  a[ 3 ] = { 3 , 2 , 1 };
  head
= InitialLinkList();
  
// CreateLinkListInRear(head,a,3);
  CreateLinkListInHead(head,a, 3 );
  printlinklist(head);
}

 

参看: http://www.cnblogs.com/emanlee/archive/2007/09/10/888942.html

转载于:https://www.cnblogs.com/emanlee/archive/2008/09/08/1286903.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值