链表反转

在知乎上看见浙大查重被查了这道题,写了一下。面试常见的一道题。

原链表:head->1->2->3->null

方法:遍历一次,头插法重新排列。

head->null

head->1->null

....

head->3->2->1->null

#include <iostream>
#include <vector>
#include <string>
using namespace std;
typedef struct ListNode {
	int val;
	ListNode *next;
	ListNode(int x) : val(x), next(NULL) {}
}ListNode;
ListNode *fun(ListNode *head)
{
	ListNode *cur = head->next;//原链表节点
	head->next = NULL;
	while (cur)//重新头插法
	{
		
		
		ListNode *behind = cur->next;
		ListNode *temp = cur;//temp和cur绑定 temp变了 cur也变了
		temp->next = head->next;
		head->next = temp;
		cur = behind;
		
		/*
		ListNode *behind = cur->next;
		cur->next = head->next;
		head->next = cur;
		cur = behind;
		*/
	}
	return head;
}
ListNode *fun(ListNode *head)//用一个pre和behind来指针反转
{
	ListNode *cur = head->next;
	//head->next = NULL;
	ListNode *pre = NULL;
	while (cur)
	{
		ListNode *behind = cur->next;
		cur->next = pre;
		pre = cur;
		cur = behind;
		if (cur == NULL) 
		{
			head->next =pre;
			break;
		}
		
	}
	return head;
}
int main()
{
	ListNode *head = new ListNode(0);
	ListNode *n1=new ListNode(1);
	ListNode *n2=new ListNode(2);
	ListNode *n3=new ListNode(3);
	head->next = n1; n1->next = n2; n2->next = n3;
	ListNode *hhh = fun(head);
	ListNode *h = hhh->next;
	while (h)
	{
		cout << h->val << endl;
		h = h->next;
	}_getch();
	return 0;
}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值