#include <stdio.h> #include <stdlib.h> typedef struct Node { int data; struct Node *next; } node; //创建一个头节点 node * create_list(int x){ node *p=(node *)malloc(sizeof(node)); p->data=x; p->next=NULL; return p; } //链表添加节点 void add_list(node *head,int x){ if(!head)return; while (head->next) { head=head->next; //当指针不为空时,表明不是最后的节点,向后移动 } node *p=(node *)malloc(sizeof(node)); //创建一个新的节点 p->data=x; p->next=NULL; head->next=p; //关联链表 } //查找节点 node * find_list(node *head,int x){ while (head&&head->data!=x) { head=head->next; //如果不是最后的节点或节点的值不相等,则指针后移 } if (head) return head; return NULL; } //打印链表的值 void print_list(node *head){ while (head) { printf("%d->",head->data); head=head->next; } printf("null\n"); } //向链表中插入值为n的元素 node * insert_list(node *head,int n,int i){ int j=0; while (head&&j<i-1) { head=head->next; j++; } if (!head) { return NULL; } node *p=(node *)malloc(sizeof(node)); //创建一个新的节点 p->data=n; p->next=head->next; head->next=p; return p; } //删除根据索引位置删除链表的位置 void delete_list(node *head,int i){ int j=0; while (head&&j<i-1) { head=head->next; j++; } //head->next=head->next->next; node *p=(node *)malloc(sizeof(node)); p=head->next; head->next=p->next; free(p); } //获取链表中的某一元素 node * get_elem(node *head,int i){ int j=0; while (head&&j<i-1) { head=head->next; j++; } if (j!=i-1) { return NULL; } printf("%d->",head->data); return head; } void main(){ node *head =create_list(1); add_list(head,5); add_list(head,3); add_list(head,7); add_list(head,8); print_list(head); insert_list(head,9,2); delete_list(head,2); get_elem(head,2); }
原文:https://www.cnblogs.com/HTLucky/p/13885350.html