https://blog.csdn.net/songsong2017/article/details/88024883 初学者参照上面博客的图
指针 <- 结点地址 有空头链表
#include<stdlib.h>
#include<stdio.h>
#include<malloc.h>
typedef struct Node {
int data;
struct Node* next;
}Node;
Node* head_insert(int n) {
Node* head = (Node*)malloc(sizeof(Node));
head->next = NULL;
while (n--) {
Node* node = (Node*)malloc(sizeof(Node));
scanf_s("%d", &node->data);
node->next = head->next;
head->next = node;
}
return head;
}
void scan_list(Node* l) {
Node* p = l;
while (p->next) {
p = p->next;
printf_s("%d", p->data);
}
}
int main() {
int n;
scanf_s("%d", &n);
Node* head = head_insert(n);
scan_list(head);
return 0;
}
Node* tail_insert(int n) {
Node* head = (Node*)malloc(sizeof(Node));
Node* tail = head;
tail->next = NULL;
Node* node;
node = head;
while (n--) {
node = (Node*)malloc(sizeof(Node));
scanf_s("%d", &node->data);
tail->next = node;
tail = node;
}
tail->next = NULL;
return head;
}
void scan_list(Node* l) {
Node* p = l;
while (p->next) {
p = p->next;
printf_s("%d\n", p->data);
}
}
int main() {
int n;
scanf_s("%d", &n);
Node* head = tail_insert(n);
scan_list(head);
return 0;
}
Node* tail_insert(int n) {
Node* head = (Node*)malloc(sizeof(Node));
Node* tail = head;
tail->next = 0;
Node* node;
node = head;
int num;
while (n--) {
node = (Node*)malloc(sizeof(Node));
scanf_s("%d", &node->data);
tail->next = node;
tail = node;
}
tail->next = NULL;
return head;
}
void insert_node(int n,int pos, Node* list) {
Node* node = (Node*)malloc(sizeof(Node));
node->data = n;
Node* p = list;
int cnt = 1;
while (p->next != NULL) {
p = p->next;
cnt++;
if (cnt == pos)break;
}
node->next = p->next;
p->next = node;
}
void scan_list(Node* l) {
Node* p = l;
while (p->next) {
p = p->next;
printf_s("%d", p->data);
}
}
int main() {
int n;
scanf_s("%d", &n);
Node* head = tail_insert(n);
insert_node(9, 3, head);
scan_list(head);
return 0;
}
void delete_node(int pos, Node* list) {
Node* p = list;
int cnt = 1;
while (p->next != NULL) {
p = p->next;
cnt++;
if (cnt == pos)break;
}
Node* q = p->next;
p->next = p->next->next;
free(q);
}
void scan_list(Node* l) {
Node* p = l;
while (p->next) {
p = p->next;
printf_s("%d", p->data);
}
}
int main() {
int n;
scanf_s("%d", &n);
Node* head = tail_insert(n);
delete_node(2, head);
scan_list(head);
return 0;
}
|