单链表反转,单链表创建,单链表尾部插入,单链表打印

本文探讨了单链表的基本操作,包括如何反转链表、创建链表、在链表尾部进行插入以及打印链表。核心思想在于理解和运用链表的指针操作,尤其是反转过程与头部插入类似。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

其实,给我感觉,单链表的反转跟链表头部是同一个原理!

#include <stdio.h>
#include <stdlib.h>

typedef struct Node{
	int num;
	struct Node *next;
}List;

int display_list(List *list);
List *create_list();
List insert_list_tail(List *head, int i);
int reverse_single_linked_list(List *list);

int main()
{
	int i;
	List *head = create_list();
	for(i=1; i<6; i++)
		insert_list_tail(head, i);
	display_list(head);
	reverse_single_linked_list(head);
	display_list(head);	
	free(head);
	return 0;
}

int display_list(List *list)
{
	List *p = list;
	if(NULL == p->next){
		printf("The list is empty!\n");
		return -1;
	}
	while(NULL != p->next){
		printf("%d->", p->next->num);
		p = p->next;
	}
	printf("\n");
	return 0;
}

List *create_list()
{
	List *list = NULL;
	list = malloc(sizeof(List));
	if(NULL == list){
		printf("malloc memory failed!\n");
		exit(-1);
	}
	// initialize head node
	list->num = '\0';
	list->next = NULL;

	return list;
}

List insert_list_tail(List *head, int i)
{
	List *new_node = NULL;
	List *p = head;

	new_node = malloc(sizeof(List));
	if(NULL == new_node){
		printf("malloc memory failed!\n");
		exit(-1);
	}
	// 1.initialize new node
	new_node->num = i;
	new_node->next = NULL;

	// 2.put the new node noto list tail
	while(NULL != p->next){
		p = p->next;
	}
	p->next = new_node;
}

int reverse_single_linked_list(List *list)
{
	if(NULL == list->next || NULL == list->next->next){
		printf("Empty list or Only one node!\n");
		return -1;
	}
	List *temp_list = list->next;
	List *cur = NULL;
	list->next = NULL;
	while(NULL != temp_list->next){
		cur = temp_list;
		temp_list = temp_list->next;
		cur->next = list->next;
		list->next = cur;
	}

	// The tail node of temp list
	temp_list->next = list->next;
	list->next = temp_list;
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值