链表相关操作

一、单链表

1、建表

#include <stdio.h>
#include <malloc.h>
#define  NULL  0    
#define  LEN    sizeof(struct cell) 
#define  OPEN  (struct cell *)malloc(LEN)

struct cell
{
    int num;    
    struct cell *next;
};

//先确定节点
int n=0; 
struct cell *creat1(int t)
{    
    struct cell  *head,*p1,*p2;    
    head=OPEN;     
    p1=p2=OPEN;//开辟空间
    while(n<t)//链表大小    
    { 
         n++;         
         if(n==1)    //头
             head->next=p1;      
         else 
             p2->next=p1; //先移p1,再移p2
         p1->num=n;         
         p2=p1;         
         If(n!=t)      //结束             
         p1=OPEN;//指向分离的新节点
    }      
    p2->next=NULL;           
    return(head);  
}

//随机输入,比如奇前偶后的排序,链表倒置之类的初值设定。
int n=0;
struct cell *creat2(void)
{    
    struct cell *head,*p1,*p2;    
    printf("Please input numbers\n");    
    head=OPEN; //指向头       
    p1=p2=OPEN;    
    scanf("%d",&p1->value);    
    while(p1->value!=0)//开辟的新节点内容为空时结束    
    {        
        n++;        
        if(n==1)
            head->next=p1;//p1和head开始时指向两个分离节点        
        else             
        {
            p2->next=p1;//p2指向p1的新节点并移动
            p2=p1;
        }        
        p1=OPEN;        
        scanf("%d",&p1->value);    
    }    
    p2->next=NULL;   
    return(head);
}
……………………
//输出链表
while(head!=NULL)
{
    printf("  %d\n",head->next->value);//每个节点内容
    head=head->next;//指向下一节点
}
………………………………

二、双链表

1、建表

#include <stdio.h>
#include <malloc.h>

#define  NULL  0    
#define  LEN    sizeof(struct cell) 
#define  OPEN  (struct cell *)malloc(LEN)
struct cell
{ 
    struct cell *prior; 
    int value; 
    struct cell *next;
};
int n=0;//节点数

struct cell *creat(void)
{ 
  struct cell *head,*p1,*p2; 
  printf("Please input numbers\n"); 
  p1=p2=OPEN; head=OPEN; 
  scanf("%d",&p1->value); 
  while(p1->value!=0) 
  { 
       n++; 
       if(n==1) 
       {
            head->next=p1; //额外的头节点 
            head->prior=NULL;//不指向任何节点 
            p1->prior=head; 
        } 
        else 
        { 
             p2->next=p1; 
             p1->prior=p2; 
             p2=p1; //移动p2 
         } 
         p1=OPEN; scanf("%d",&p1->value);//输入新节点内容 
     } 
     p2->next=NULL; 
     return(head);
  }



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值