链表的逆转

法1:

 

代码: 

#include<iostream>
#include<fstream>
#include<string>
#include<cstdio>
using namespace std;
#define ERROR 0
typedef struct LNode {
	int data;
	struct LNode *next;
} LNode, *List;
void InitList(List &L);
void ListInput(List &L, int n);
void ListOutput(List L);
void reverse(List &L);
int main() 
{
	int n;
	List LA;
	InitList(LA);
	cin >> n;
	ListInput(LA, n);
	reverse(LA);
	ListOutput(LA);
	return 0;
}
void reverse(List &L)
{
	List p,q;
	p=L->next;
	L->next=NULL;
	while(p)
	{
		q=p->next;
		p->next=L->next;//新p指旧p,p更新之前存到了L->next中
		L->next=p;//L->next指当前p
		p=q;//p后移gengxin,最后p空
	}
}
void InitList(List &L) 
{
	L = new LNode;
	L->next = NULL;
}

void ListInput(List &L, int n) 
{
	int i = 1;
	List p, r;
	r = L;
	while (i <= n) {
		p = new LNode;
		cin >> p->data;
		p->next = NULL;
		r->next = p;
		r = p;
		i++;
	}
}
void ListOutput(List L) 
{
	List p;
	p = L->next;
	while (p != NULL) {
		cout << p->data << " ";
		p = p->next;
	}
}

法二(有些复杂)

#include<iostream>
#include<fstream>
#include<string>
#include<cstdio>
using namespace std;

#define ERROR 0

typedef struct LNode {
	int data; //结点的数据域
	struct LNode *next; //结点的指针域
} LNode, *List; //LinkList为指向结构体LNode的指针类型

void InitList(List &L); //创建链表(带头结点)
void ListInput(List &L, int n); //链表数据的输入
void ListOutput(List L); //输出List
bool LocateElem(List L, int e); //判断List里有没有e这个元素
void reverselist(List &L,int n);
int main() 
{
	int n;//定义链表中输入元素的个数 
	List LA;
	InitList(LA);
	cin>>n;
	ListInput(LA, n);
    reverselist(LA,n);
	ListOutput(LA);
	return 0;
}

void ListInput(List &L, int n) //链表数据的输入
{
	int i=1;
	List p, r;
	r = L;
	while (i<=n) {
		p = new LNode;
		cin >> p->data;
		p->next = NULL;
		r->next = p;
		r = p;
		i++;
	}
}
void ListOutput(List L) //输出List
{
	List p;
	p = L;
	//cout << "The List is:"<<endl;
	while (p ->next!= NULL) {
		cout << p->data << " ";
		p = p->next;
	}
	cout << endl;
}

void InitList(List &L) //创建链表
{
	L = new LNode;
	L->next = NULL;
}
//查找线性表中是否包含元素e
bool LocateElem(List L, int e)
{
	List p;
	InitList(p);
	p=L->next;
	while(p->next!=NULL)
	{	
		if(p->data==e)
		{
			return true;
		}
		p=p->next;
	}
	return false;
}
void reverselist(List &L,int n)
{
	List p,q,r;
	if(n==2)
	{
		p=L;
		q=L->next;
		L->next=NULL;
		r=q->next;
		q->next=p;
		p=q;
		q=r;q->next=p;
		L=q;
	}
	if(n==1)
	{
	  List p;
		p=L->next;
		L->next->next=L;
		L->next=NULL;
		L=p;
	}
	else{
		p=L;
		q=L->next;
		r=q->next;
		int k=1;
		while(r->next!=NULL)
		{   
			if (k==1)
			{
				q->next=p;
				p->next=NULL;
				p=q;
				q=r;
				r=r->next;
				k++;
			}
			else 
			{
				q->next=p;
				p=q;
				q=r;
				r=r->next;
			}
			
		}q->next=p;p=q;q=r;q->next=p;L=q;
	}

	

		

	//L->next=NULL;
	
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值