链表的创建、删除、反向(C语言)

来源:互联网 发布:唱歌 台风 知乎 编辑:程序博客网 时间:2024/05/17 02:58

好久没接触C了,今天温习一下链表操作。

链表反向用的方式是新建一个链表,将原链表元素依次插入至新链表头部,实现反向。

链表删除是参考了linus的方法,用一个二级指针,省去了教科书中方式关于链表头部的判断。

#include <stdio.h>#include <malloc.h>typedef struct Node_s{int value;struct Node_s *next;}Node_t;void InsertNode(Node_t **List,int value) {Node_t *node = (Node_t *)malloc(sizeof(Node_t));node->value = value;if(*List != NULL){Node_t *current = *List;Node_t *pre = *List;while(current != NULL && value > current->value){pre = current;current = current->next;}node->next = current;pre->next = node;}else{node->next = NULL;*List = node;}}void RemoveNode(Node_t **List,int value){Node_t **current = List;while(*current != NULL){if(IsNode(*current,value)){current = &((*current)->next);}else{Node_t *node = *current;*current = (*current)->next;free(node);break;}if((*current)->value >value){  //因为是有序链表,所以超过范围可以判断此链表中无删除元素break;}}}void InsertHead(Node_t **List,int value){Node_t *node = (Node_t *)malloc(sizeof(Node_t));node->value = value;node->next = *List;*List = node;}void ReverseList(Node_t **List){Node_t *RList = NULL;  //新链表Node_t *current = *List;while(current){InsertHead(&RList,current->value); //将元素依次插入至新链表Node_t *node = current;current = current->next;free(node);}*List = RList;}int IsNode(Node_t *Node,int value){return ((Node->value != value)); //是否符合条件}int main(int argc,char **argv){Node_t *List = NULL;InsertNode(&List,2);InsertNode(&List,5);InsertNode(&List,3);ReverseList(&List);if(List != NULL){printf("%d\n",List->value); //这里可以加断点进行调试信息查看}return 0;}




0 0
原创粉丝点击