链表的基本操作有四种:建立,插入,删除,遍历
在程序里面如下:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct student {
char name[10];
struct student *next;
}* st_ptr;
void print_st(st_ptr head) {
st_ptr tmp = head;
while (tmp->next) {
printf("%s\n", tmp->next->name);
tmp = tmp->next;
}
printf("\n");
}
int add_st(st_ptr head, int add, st_ptr new) {
st_ptr tmp = head;
int pos = 0;
while (tmp->next) {
pos++;
if (pos == add) {
new->next = tmp->next->next;
tmp->next->next = new;
return 0;
}
tmp = tmp->next;
}
return -1;
}
int del_st(st_ptr head, int del) {
st_ptr tmp = head;
int pos = 0;
while (tmp->next) {
pos++;
if (pos == del) {
tmp->next->next = tmp->next->next->next;
return 0;
}
tmp = tmp->next;
}
return -1;
}
int main()
{
st_ptr head, first, second;
head = (st_ptr)malloc(sizeof(struct student));
first = (st_ptr)malloc(sizeof(struct student));
second = (st_ptr)malloc(sizeof(struct student));
head->next = first;
strcpy(first->name, "cherry");
first->next = second;
strcpy(second->name, "cheny");
second->next = NULL;
print_st(head);
st_ptr new = (st_ptr)malloc(sizeof(struct student));
strcpy(new->name, "new");
if (add_st(head, 2, new) == -1) {
printf("add error\n");
}
print_st(head);
if (del_st(head, 1) == -1) {
printf("del error\n");
}
print_st(head);
return 0;
}
这些是最基本的操作,也是最基础的操作