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

好久没接触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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值