20170814_逆置单链表

20170814_逆置单链表(2种方法)


/*输入一个单链表的头指针head,输出该单链表的逆置单链表。
*/

#include<iostream>
#include<vector>
#include<algorithm>
#include<numeric>
using namespace std;

//单链表节点
struct ListNode
{
	int val;
	ListNode *next;
	ListNode(int x):val(x),next(nullptr) {}
};
//尾插法建立一个单链表
ListNode *CreatList(const vector<int> &a)
{
	int ListSize=a.size();
	if(ListSize<1)
		return nullptr;
	else
	{
		ListNode *root=new ListNode(a[0]);
		ListNode *r=root;
		for(int i=1; i<ListSize; ++i)
		{
			ListNode *s=new ListNode(a[i]);
			r->next=s;
			r=s;
		}
		return root;
	}
}
//顺序输出一个单链表
void OutList(ListNode *root)
{
	ListNode *p=root;
	while(p!=NULL)
	{
		if(p->next!=NULL)
			cout<<p->val<<", ";
		else
			cout<<p->val;
		p=p->next;
	}
	cout<<endl;
}
//逆置单链表1:使用头插法逆置
ListNode *ReverseList(ListNode *head)
{
	if(head==nullptr || head->next==nullptr)
		return head;
	ListNode *temp=new ListNode(0);
	temp->next=head;
	head=head->next;
	temp->next->next=nullptr;
	ListNode *pNext=nullptr;
	while(head)
	{
		pNext=head->next;
		head->next=temp->next;
		temp->next=head;
		head=pNext;
	}
	head=temp->next;
	delete temp;
	temp=nullptr;
	return head;
}

//逆置单链表2:原地逆转法(面试时候倾向于这个简单明了的方法!)
ListNode *ReverseList2(ListNode *head)
{
	if(head==nullptr || head->next==nullptr)
		return head;
	ListNode *pPre=nullptr;
	ListNode *pNext=nullptr;
	while(head)
	{
		pNext=head->next;
		head->next=pPre;
		pPre=head;
		head=pNext;
	}
	head=pPre;
	return head;
}

int main(void)
{
	int num[]={1,2,3,4,5,6,7,8,9,10,100,200,300,400};
	vector<int> a(begin(num),end(num));
	ListNode *root=CreatList(a);
	cout<<"单链表建立完成."<<endl;

	cout<<"顺序输出单链表:";
	OutList(root);
	cout<<endl;

	cout<<"方法1:逆置单链表:";
	ListNode *head=ReverseList(root);
	OutList(head);
	cout<<endl;

	cout<<"方法2:逆置单链表:";
	ListNode *head2=ReverseList(head);
	OutList(head2);
	cout<<endl;

	system("pause");
	return 0;
}






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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值