#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<math.h>
#include<string.h>
#include<stdlib.h>
#define LEN sizeof(node)
typedef struct Node{
int data;
struct Node * next;
}node;//定义结点node
void creat_link(node *head){
head->next = NULL;
node *h = (node *)malloc(LEN);
h = head;
if (h!=NULL)
for (int i = 1; i <= 6; i++){
node * p = (node *)malloc(LEN);
p->data = i;
p->next = h->next;
h->next = p;
h=p;//尾插法
}
}
void printf_link(node * head){//打印结点
node *p = (node *)malloc(LEN);
p = head->next;
if (head !=NULL)
while (p != NULL){
printf("%-4d", p->data);
p = p->next;
}
putchar('\n');
}
void insert_node(node *head, int n){ //增加一结点 插入位置在第n个结点位置
node *h = (node *)malloc(LEN);
node *insert = (node *)malloc(LEN);
h = head->next;
if (head != NULL){
for (int i = 1; i < n-1; i++)
h = h->next;
}
insert->data = 111 ;
insert->next = h->next;
h->next = insert;
}
void delete_node(node *head, int n){//删除指定位置的结点
node *h = (node *)malloc(LEN);
node * p = (node *)malloc(LEN);
h = head->next;
if (h != NULL){
for (int i = 1; i < n-1; i++){
h = h->next;
}
p = h->next;
h->next = p->next;
free(p);
}
}
void update_node(node *head, int n, int m){//修改某一结点的数据域
node *h = (node *)malloc(LEN);
h = head->next;
if (h != NULL){
for (int i = 1; i < n; i++)
h = h->next;
h->data = m;
}
}
void search_node(node *head, int m)
{//查找某一结点
node *h = (node *)malloc(LEN);
int count = 0;
h = head->next;
if (head != NULL){
while (h != NULL){
count++;
if (h->data == m)
break;
h = h->next;
}
}
if (h == NULL) printf("未找到\n");
else
printf("已找到 ,在第%d结点\n", count);
}
int main(){
node *head = (node *)malloc(LEN);
creat_link(head);
printf_link(head);
insert_node(head,4);
printf_link(head);
delete_node(head, 4);
printf_link(head);
update_node(head, 4, 111);
printf_link(head);
search_node(head, 6);
return 0;
}
提示:本人在学习链表中,后期会详细讲解单链表内容.