链表反转

###非递归实现

//思路为将节点从前到后依次放到表头, 最少需要3个指针
 ListNode * ReverseList(ListNode *list )
 {
     ListNode *head = NULL;
     ListNode *current = list;          
     ListNode *next = NULL;
 
     while (current != NULL) {          
         next = current->m_pNext;       
         current->m_pNext = head;       
         head = current;                
         current = next;                
     }
    
     return head;                       
 }  

递归实现

ListNode * ReverseList2(ListNode * list)
 {
     //如果链表为空或者链表中只有一个元素
     if(list == NULL || list->m_pNext == NULL)    
         return head;
 
     ListNode * head = ReverseList2(list->m_pNext);//先反转后面的链表
     list->m_pNext->m_pNext = list;//再将当前节点设置为其然来后面节点的后续节点
     list->m_pNext = NULL;

     return head;
 }

###完整程序

#include <stdlib>
#include <iostream>
using namespace std;
 
//定义一个链表节点
 typedef struct ListNode
{
	int       m_nKey;
	struct ListNode * m_pNext;
}ListNode;
 
//插入一个新节点到链表中(放在链表头部)
void CreateList(ListNode * & head,int data)
{
	//创建新节点
    ListNode * p=(ListNode*)malloc(sizeof(ListNode));
	p->m_nKey=data;
	p->m_pNext=NULL;
 
	if(head==NULL)
	{
		head=p;
		return;
	}
	p->m_pNext=head;
	head=p;
}
 
void  printList(ListNode* head)
{
   ListNode * p=head;
   while(p!=NULL)
   {
      cout<<p->m_nKey<<" ";
	  p=p->m_pNext;
   }
   cout<<endl;
}
 
//思路为将节点从前到后依次放到表头, 最少需要3个指针
ListNode * ReverseList(ListNode *list )
{
	ListNode *head = NULL;
	ListNode *current = list; 
	ListNode *next = NULL;

	while (current != NULL) {
		next = current->m_pNext;
		current->m_pNext = head;
		head = current;
		current = next; 
	}

	return head;
}
 
//递归方式
ListNode * ReverseList2(ListNode * head)
{
	//如果链表为空或者链表中只有一个元素
	if(head==NULL || head->m_pNext==NULL)
		return head;

	ListNode * newhead=ReverseList2(head->m_pNext);//先反转后面的链表
	head->m_pNext->m_pNext=head;//再将当前节点设置为其然来后面节点的后续节点
	head->m_pNext=NULL;
	return newhead;
}
 
int main()
{
	ListNode * Head=NULL;
    for(int i=0;i<10;i++)
      CreateList(Head,i);
    printList(Head);
    Head=ReverseList2(Head);
    printList(Head);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值