您的位置:首页 > 编程语言 > C语言/C++

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

2014-08-30 16:39 447 查看
好久没接触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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐