C语言之单链表(增删改查逆)

来源:互联网 发布:大数据分析用的数据库 编辑:程序博客网 时间:2024/06/05 11:50
单链表的增删该查逆#include <stdio.h>#include <stdlib.h>#define FALSE 0#define TRUE  1typedef struct _node   //创建结构体{int data;struct _node *next;   //创建一个结构体指针}Node;int head_insert(Node **h,int data)  //头插法{if(h == NULL){return 0;}Node *node = (Node *)malloc(sizeof(Node) / sizeof(char));  //创建一个新的节点if(node == NULL){return 0;}node->data = data;   //头插法关键代码node->next = *h;*h = node;return 1;}int last_insert(Node **h,int data){if(h == NULL){return FALSE;}Node *node = (Node *)malloc(sizeof(Node) / sizeof(char));    //创建一个新的节点if(node == NULL)   //判断节点是否建立成功{return FALSE;}node->data = data;    //新节点的初始化node->next = NULL;Node *tmp = *h;if(tmp == NULL)   //判断链表是否为空{*h = node;}else{while(tmp->next)   //尾插法关键代码{tmp = tmp->next;}tmp->next = node;}return TRUE;}void Display(Node *h)  //打印链表值的函数{if(h == NULL){return;}int count = 0;while(h){if(count++ % 4 == 0){printf("\n");}printf("%8d",h->data);h = h->next;}printf("\n");}int pos_insert(Node **h,int pos,int data)   //随机插入链表{if(h == NULL || pos < 1){return FALSE;}Node *node = (Node *)malloc(sizeof(Node) / sizeof(char));   //创建一个新的节点if(node == NULL){return FALSE;}node->data = data;node->next = NULL;Node *tmp = *h;if(*h == NULL)   //判断链表是否为空{if(pos != 1){printf("该表为空表,无法插入数据\n");return FALSE;}node->next = NULL;//如果输入插入的为值是1,则直接插在空链表的后面*h = node;}else                   //随机插入关键代码{if(pos == 1){node->next = tmp->next;tmp->next = node;}else{int i;for(i = 0;i < pos - 2;i++){if(!tmp){printf("插入的数越界\n");return FALSE;}tmp = tmp->next;}node->next = tmp->next;tmp->next = node;}}return TRUE;}int Delete_pos(Node **h,int pos)           //随机删除链表的节点{if(h == NULL || *h == NULL || pos < 1){return FALSE;}Node *tmp = *h;if(pos == 1){*h = tmp->next;free(tmp);}else                           ////随机删除关键代码{int i;for(i = 0;i < pos - 2;i++){if(tmp->next == NULL){printf("删除的数越界\n");return FALSE;}tmp = tmp->next;}Node *p = tmp->next;tmp->next = p->next;free(p);}return TRUE;}int Reverse_list(Node **h)               //链表逆序{if(h == NULL || *h == NULL || (*h)->next == NULL){return FALSE;}Node *pre = *h;Node *cur = (*h)->next;Node *tmp;while(cur){tmp = cur->next;cur->next = pre;pre = cur;cur = tmp;}(*h)->next = NULL;*h = pre;return TRUE;}
int Clean_List(Node *h)     //删除节点{if(h == NULL){return FALSE;}while(h->next){pos_delete(h,1);}return TRUE;}
int main(){Node *head = NULL;int i;for(i = 0; i < 10;i++){//head_insert(&head,i);last_insert(&head,i);}//pos_insert(&head,10,100);//Delete_pos(&head,5);Display(head);Reverse_list(&head);Display(head);return 0;}

原创粉丝点击