接翁恺C语言进阶,链表的学习笔记(一)
6、学习了将数据放入进链表,但是不知道是否放进去了,在前面的笔记中我是将链表的第一位,或者最后一位输出了出来。这里我将会把链表进行遍历输出。
#include <stdio.h>
#include <stdlib.h>
#include "node.h"
typedef struct _list{
Node* head;
Node* tail;
}List;
void * add(List *plist,int number);
void print(List *pList);/*这就是将链表遍历输出的子函数*/
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);
print(&list);
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;
}
}
/*这就是将链表遍历输出的子函数*/
void print(List *pList)
{
Node *p;
for(p=pList->head;p;p=p->next)//结束的条件是p不存在 //这就是链表的遍历,将链表里存储的东西从头输出到尾。
{
printf("%d\t",p->value);
}
}
7、对链表进行简单的操作,输入一个数,搜索链表中是否有所存储。
#include <stdio.h>
#include <stdlib.h>
#include "node.h"
typedef struct _list{
Node* head;
Node* tail;
}List;
void * add(List *plist,int number);
void print(List *pList);/*这就是将链表遍历输出的子函数*/
void found(List *fList);/*这是输入一个数,搜索链表中是否有所存储的子函数。*/
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);
print(&list);
scanf("%d",&number);
/**/
Node *p;
int isFound=0;
for(p=list.head;p;p=p->next)
{
if(p->value==number){
printf("找到了");
isFound=1;
break;
}
}
if(!isFound){
printf("没有找到");
}
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;
}
}
/*这就是将链表遍历输出的子函数*/
void print(List *pList)
{
Node *p;
for(p=pList->head;p;p=p->next)//结束的条件是p不存在 //这就是链表的遍历,将链表里存储的东西从头输出到尾。
{
printf("%d\t",p->value);
}
}
/*这是输入一个数,搜索链表中是否有所存储的子函数。*/
void found(List *fList)
{
int number=0;
scanf("%d",&number);
Node *p;
int isFound=0;
for(p=fList->head;p;p=p->next)
{
if(p->value==number){
printf("找到了");
isFound=1;
break;
}
}
if(!isFound){
printf("没有找到");
}
}
思考:搜索存储的数据,将scanf函数封装在子函数里,还是放在函数外。我这是放在函数里的。
8、删除链表中所储存的一个数。(注意这个程序所以只会删除搜索到的第一个数),这里只将子函数给出来了。其他部分同上。
void delete(List *fList)
{
int number;
scanf("%d",&number);
Node *p;
Node *q;
for(q=NULL,p=fList->head;p;q=p,p=p->next)
{
if(p->value==number)
{
if(q)//保证q是可操作的,如果没有这个if,当所要删除的数是在第一个位置时,将会出现错误。
{
q->next=p->next;
}
else
{
fList->head=p->next;
}
free(p);
break;
}
}
}