浙大数据结构笔记-单链表
#include <stdio.h>
#include <stdlib.h>
#include "node.h"
//typedef struct _node{
// int value;
// struct _node *next;
//} Node;
typedef struct _list{
Node *head;
} List;
void add(List *pList, int number);
void print(List *pList);
int main(int argc, char *argv[]) {
List list;
int number;
list.head = NULL;
do {
scanf("%d", &number);
if (number != -1) {
add(&list, number);
}
} while(number != -1);
print(&list);
scanf("%d", &number);
Node *p;
//find number
int isFound = 0;
for ( p=list.head; p; p=p->next ) {
if ( p->value == number ) {
printf("found\n");
isFound = 1;
break;
}
}
if(!isFound){
printf("not found\n");
}
//find number and delete corresponding linked list
Node *q;
for ( q=NULL, p=list.head; p; q=p, p=p->next ) {
if ( p->value == number ) {
if ( q ) {
q->next = p->next;
} else {
list.head = p->next;
}
free(p);
break;
}
}
for ( p=list.head; p; p=q) {
q = p->next;
free(p);
}
return 0;
}
void print(List *pList){
Node *p;
for(p=pList->head; p; p=p->next){
printf("%d\t", p->value);
}
printf("\n");
}
void add(List* pList, int number) {
Node *p = (Node*)malloc(sizeof(Node));
p->value = number;
p->next = NULL;
//find the last
Node *last = pList->head;
if(last) {
while(last->next) {
last = last->next;
}
last->next = p;
} else {
pList->head = p;
}
}
代码来自:
1.https://www.icourse163.org/learn/ZJU-9001#/learn/content?type=detail&id=200049