C:反转链表

325 篇文章 3 订阅 ¥299.90 ¥399.90

反转链表经常作为面试题,看过的解答写的都不够清晰易懂。

我是这样认为的:反转链表其实就是把链表中的节点从头部依次取出,然后再其加入到另一个链表,这个过程即完成了链表的反转。

#include <stdio.h>

struct Node{
	int data;
	struct Node *next;
};

struct Node* popFromHead(struct Node **head)
{
	if(*head != 0 )
	{
		struct Node* first = *head;
		*head = first->next;
		return first;
	}
	else
	{
		return 0;
	}
}

void pushToHead(struct Node** head, struct Node* t)
{
	t->next = *head;
	*head = t;
}

void printList(struct Node *head)
{
	while(head != 0)
	{
		printf("%d ", head->data);
		head = head->next;
	}
	printf("\n");
}

int main()
{
	struct Node *head = 0;
	struct Node n1, n2, n3;
	n1.data = 1;
	n2.data = 2;
	n3.data = 3;
	pushToHead(&head, &n3);
	pushToHead(&head, &n2);
	pushToHead(&head, &n1);
	printList(head);

	struct Node* pNode = 0;
	struct Node* reverseList = 0;

	while((pNode = popFromHead(&head)) != 0)
	{
		pushToHead(&reverseList, pNode);
	}
	printList(reverseList);
    return 0;
}

运行程序输出:
1 2 3 
3 2 1 
可见链表被反转了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

风静如云

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值