单链表类型定义
单链表是由一串结点组成的,其中每个结点都包含指向下一个结点的指针,最后一个结点的指针为空;
假设结点只包括一个整数和指向下一结点的指针
typedef struct node{int data;struct node *next;
}LNode,*LinkList;
//LNode为结构类型,LinkList为LNode结构的指针类型
单链表的建立
画图理解帮助记忆~
头插法
#include<stdio.h>
#include<malloc.h>
typedef struct node{int data;struct node *next;
}LNode,*LinkList;
//LNode为结构类型,LinkList为LNode结构的指针类型
int main(){//头插法建立单链表,输入-1表示结束int num;LinkList p;LinkList head;head=(LinkList)malloc(sizeof(LNode));head->next=NULL;while(scanf("%d",&num),num!=-1){p=(LinkList)malloc(sizeof(LNode));p->data=num;p->next=head->next;head->next=p;}p=head->next;while(p!=NULL){printf("%d ",p->data);p=p->next;}return 0;
}
尾插法
#include<stdio.h>
#include<malloc.h>
typedef struct node{int data;struct node*next;
}LNode,*LinkList;
int main(){//尾插法建立单链表,输入-1表示结束 int num;LinkList head,p,rear;head=(LinkList)malloc(sizeof(LNode));head->next=NULL;rear=head;while(scanf("%d",&num),num!=-1){p=(LinkList)malloc(sizeof(LNode));p->data=num;rear->next=p;/*循环执行第一次时,head与rear相等,所指的内容相等 所以通过rear将它们共同所指的内容修改后head所指的内容也会修改 */rear=p;}rear->next=NULL;p=head->next;while(p){printf("%d ",p->data);p=p->next;}return 0;
}