就地翻转单链表

翻转单链表是比较简单的事情,就像双向链表插入节点一样,关键在于指针的处理,除此之外没有什么值得关注的!

#include <iostream>
using namespace std;

struct list {
	int value;
	struct list *next;
};

struct list *insert(struct list *head, int v)
{
	if (head) {
		head->next = insert(head->next, v);
	} else {
		head = new struct list;
		head->value = v;
		head->next = 0;
	}
	return head;
}

struct list *reverse(struct list *head)
{
	struct list *prev = 0, *next = 0;
	while (head) {
		next = head->next;
		head->next = prev;
		prev = head;
		head = next;
	}
	return prev;
}

void print(struct list *head)
{
	cout << "list: ";
	while (head) {
		cout << head->value;
		if (head->next) {
			cout << "->";
		}
		head = head->next;
	}
	cout << endl;
}

int main()
{
	struct list *head1 = 0;
	head1 = insert(head1, 0);
	head1 = insert(head1, 1);
	head1 = insert(head1, 2);
	head1 = insert(head1, 3);
	head1 = insert(head1, 4);
	head1 = insert(head1, 5);
	head1 = insert(head1, 6);
	head1 = insert(head1, 7);
	head1 = insert(head1, 8);
	head1 = insert(head1, 9);
	print(head1);
	head1 = reverse(head1);
	print(head1);
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值