用指针写的链表
从刚开始就没有彻底理解链表的原理,所以一直就是背的板子。直到今天学了指针,拿指针写链表,才觉得很透彻。指针的思路真的比数组清晰很多。
#include<cstdio>
#include<iostream>
#include<cstdlib>
using namespace std;
struct Node {
int value;
Node* next;
};
struct List {
Node* head;
Node* last;
};
void add_Node(List* list, int number) {
Node* p = (Node*)malloc(sizeof(Node));
p->value = number;
p->next = NULL;
if (list->head) { //head is not NULL
list->last->next = p;
list->last = p;
} else {
list->head = p;
list->last = p;
}
}
void output(List* list) {
for (Node* p = list->head; p; p = p->next)
printf("%d ", p->value);
}
void delete_Node(List* list, int number) {
for (Node* q = NULL, *p = list->head; p; q = p, p = p->next) {
if (p->value == number) {
if (q != NULL) {
q->next = p->next;
free(p);
p = q->next;
} else {
list->head = p->next;
free(p);
q = NULL;
p = list->head;
}
}
}
}
void free_linked_list(List* list) {
for (Node* p = list->head, *q; p; p = q) {
q = p->next;
free(p);
}
}
int main() {
int number;
List list;
list.head = list.last = NULL;
do {
scanf("%d", &number);
//Attach
if (number != -1)
add_Node(&list, number);
} while(number != -1);
output(&list);
scanf("%d", &number);
delete_Node(&list, number);
output(&list);
free_linked_list(&list);
return !printf("\n");
}