(数据结构)线性表_单链表反转 _模仿

方法1:

#include<stdio.h>   
#include<stdlib.h>   
#include<malloc.h>   

typedef int ElemType;  
  
typedef struct Node *List;
typedef struct Node *Position;
typedef struct Node Node;

struct Node
{
	ElemType Element;
	List next;
};

int length_List(List L)  //L带头结点
{
	int len;
    Position temp;  
	temp=L;
	while(temp->next!=NULL)
	{
		temp=temp->next;
		len++;
	}
	return len;
}

List ReverseList(List L)  //反转单链表函数,L带头结点
{
	if(L->next->next==NULL||L->next==NULL)  //空链表或者只有一个结点
		return L;

	List Result ,temp;  //使用这两个结构体变量,起保护L作用
	int len ,i;

	Result=(List)malloc(sizeof(Node));  
    Result->next=NULL;

    len=length_List(L);

	for(i=0;i<len;i++)
	{
        temp=(List)malloc(sizeof(Node)); 
		temp->Element=L->next->Element;  //临时链表结点,用来存放L链表中的元素

		temp->next=Result->next;
        Result->next=temp;

        L=L->next;
	}
	return Result;
}

方法2:

#include<stdio.h>   
#include<stdlib.h>   
#include<malloc.h>   

typedef int ElemType;  
  
typedef struct Node *List;
typedef struct Node *Position;
typedef struct Node Node;

struct Node
{
	ElemType Element;
	List next;
};

List ReverseList(List L1)  //反转单链表函数,L1带头结点
{
	if(L1->next==NULL||L1->next->next==NULL)
		return L1;

	Position PreviousPos ,CurrentPos ,NextPos;  
	List L;
	L=L1->next;  //L无头结点,为处理方便
	PreviousPos=NULL;
	CurrentPos=L;
	NextPos=L->next;

	while(NextPos!=NULL)
	{
		CurrentPos->next=PreviousPos;
		PreviousPos=CurrentPos;
		CurrentPos=NextPos;
		NextPos=NextPos->next;
	}
    CurrentPos->next=PreviousPos;
	return CurrentPos;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值