单链表基本操作(1)

来源:互联网 发布:动态字幕制作软件 编辑:程序博客网 时间:2024/05/22 10:33

单链表基本操作

创建

  • 创建
  • 头插入加载
  • 尾插入加载

创建空链表

创建一个单链表,且为空表,并且返回链表
创建结构类型,在CS.c文件中

typedef struct node{    int data;    struct node *next;}LINKLIST;

在Link.h写出方法声明

#include <stdio.h>#include "CS.c"/* 创建一个空单链表 */LINKLIST *inill();

在Link.c中实现此方法

#include "Link.h"LINKLIST *inill(){    LINKLIST *L;    L=(LINKLIST *)malloc(sizeof(LINKLIST));    L->next=NULL;    L->data=-1;    return (L);}

声明一个链表变量,并且分配空间,设置next指针域为NULL,data数据域为-1.

在main.c中调用此方法,并且进行判断

#include <stdio.h>#include "Link.h"int main(int argc, const char * argv[]) {    //创建了空的链表    LINKLIST *linklist=inill();    printf("inill() method  create is a null  line %d \n",linklist->next==NULL);    return 0;}

根据定义:头结点的指针域存放指向首节点的指针,当链表为空时,首节点的指针为空,即:头结点的指针域为空.

打印数据:
inill() method create is a null line 1
所以为linklist为空链表

头插入加载

link.h

/* 头插入加载 */LINKLIST * loadHead();

link.c

LINKLIST * loadHead(){    LINKLIST *p,*Q;    int x;    Q=(LINKLIST *)malloc(sizeof(LINKLIST));    Q->data=-1;    Q->next=NULL;    printf("please input the integer to inster\n");    scanf("%d",&x);    while (x!=-1) {        p=(LINKLIST *) malloc(sizeof(LINKLIST));        p->data=x;        p->next=Q->next;        Q->next=p;        scanf("%d",&x);    }    return Q;}

1.先创建一个空链表Q
2.然后从键盘输入 x
3.这里写图片描述

main.c

 //头插入    LINKLIST *headInsertList=loadHead();    printf("headInsertList=[");    while (headInsertList!=NULL) {        if(headInsertList->data==-1){            printf("%d",headInsertList->data);        }else{            printf(",%d",headInsertList->data);        }        headInsertList=headInsertList->next;    }    printf("]\n");

打印结果:

please input the integer to inster12345-1headInsertList=[-1,5,4,3,2,1]

尾插入加载

link.h

/* 尾插入加载 */LINKLIST * loadRear();

link.c

LINKLIST * loadRear(){    LINKLIST *q,*Q,*R;    Q=(LINKLIST *) malloc(sizeof(LINKLIST));    R=Q;    Q->data=-1;    Q->next=NULL;    int x;    printf("please insert integer \n");    scanf("%d",&x);    while (x!=-1) {        q=(LINKLIST *) malloc(sizeof(LINKLIST));        q->data=x;        q->next=NULL;        Q->next=q;        Q=q;        scanf("%d",&x);    }    return R;}

解释
1.创建了一个空链表Q,并且付给了R,
2.从键盘输入x
3.输入的数据不为-1
3.1创建一个空链表q
3.2设置q的数据域为x q->data=x;
3.3设置q的指针域为NULL
3.4设置Q的指针域为输入的q
3.5最后把刚创建的链表赋给Q,供下次再次插入的时候使用,这是关键的一步操作
4.最后把R返回,表示链表的头指针
这里就不做流程图了,就是按照的是头插入加载差不多

main.c

//尾插入    LINKLIST *lastInsertList=loadRear();    printf("lastInsertList=[");    while (lastInsertList!=NULL) {        if(lastInsertList->data==-1){            printf("%d",lastInsertList->data);        }else{            printf(",%d",lastInsertList->data);        }        lastInsertList=lastInsertList->next;    }    printf("]\n");

打印结果:

please insert integer 12345-1lastInsertList=[-1,1,2,3,4,5]Program ended with exit code: 0

源码下载

0 0
原创粉丝点击