链表的学习
课堂链接
https://www.icourse163.org/learn/ZJU-200001?tid=1207389210#/learn/content?type=detail&id=1212809729&cid=1216239425
1,链表的建立
#include <stdio.h>
#include <stdlib.h>
#include "node.h"
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
typedef struct _node{
int value;
struct _node *next;
}Node;
Node* add(Node *head,int number);
int main(int argc, char *argv[])
{
Node *head=NULL;//初始化
int number;
do{
scanf("%d",&number);
if(number!=-1){
//add to linked-list
Node *p=(Node*)malloc(sizeof(Node));
p->value=number;
p->next=NULL;
find the last
Node *last=head;
if(last){
while(last->next){//遍历到last->next=NULL为止,保证数据存储在链表的最后一位
last=last->next;
}
last->next=p;
}else{
head=p;
}
}
}while(number!=-1);
printf("%d",head->value);//这一步是为了验证我们把值传了进去,输出的是第一节储存的值
return 0;
}
2、将其封装成函数
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
typedef struct _node{
int value;
struct _node *next;
}Node;
Node* add(Node *head,int number);
int main(int argc, char *argv[])
{
Node *head=NULL;
int number;
do{
scanf("%d",&number);
if(number!=-1){
head=add(head,number);
}
}while(number!=-1);
printf("%d",head->value);
return 0;
}
Node* add(Node *head,int number)
{
Node *p=(Node*)malloc(sizeof(Node));
p->value=number;
p->next=NULL;
Node *last=head;
if(last){
while(last->next){
last=last->next;
}
last->next=p;
}else{
head=p;
}
return head;// 注:改进3、void add(Node **head,int number)当这么定义函数时就不需要返回值
}
4、再次改进
优点:用了我们自己定义的一种数据list,代表整个链表,方便以后做修改。eg:可以在定义一个数据,让链表存储不需要总是从第一位开始搜寻,而直接从最后一位开始存储
#include <stdio.h>
#include <stdlib.h>
typedef struct _node{
int value;
struct _node *next;
}Node;
typedef struct _list{
Node* head;
}List;
void * add(List *list,int number);
int main(int argc, char *argv[])
{
List list;
list.head=NULL;
int number;
do{
scanf("%d",&number);
if(number!=-1){
add(&list,number);
}
}while(number!=-1);
printf("%d",list.head->value);
return 0;
}
void * add(List *list,int number)
{
Node *p=(Node*)malloc(sizeof(Node));
p->value=number;
p->next=NULL;
//find the last
Node *last=list->head;
if(last){
while(last->next){
last=last->next;
}
last->next=p;
}else{
list->head=p;
}
}
5、就是将4的例子实现
#include <stdio.h>
#include <stdlib.h>
#include "node.h"
typedef struct _list{
Node* head;
Node* tail;
}List;
void * add(List *list,int number);
int main(int argc, char *argv[])
{
List list;
list.head=NULL;
list.tail=NULL;
int number;
do{
scanf("%d",&number);
if(number!=-1){
add(&list,number);
// head=add(head,number);
}
}while(number!=-1);
printf("%d",list.tail->value);
return 0;
}
void * add(List *plist,int number)
{
Node *p=(Node*)malloc(sizeof(Node));
p->value=number;
p->next=NULL;
//find the last
Node *last=plist->tail;
if(last){
// while(last->next){
// last=last->next;
// }
last->next=p;
plist->tail=p;
}else{
plist->head=p;
plist->tail=p;
}
}