单链表反转

本文介绍了一段使用C语言实现的链表翻转算法,通过递归和迭代两种方式,展示了如何将链表节点顺序颠倒。代码示例包括了链表的创建、翻转过程以及验证翻转是否成功的输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

struct list
{
  int data;
  struct list *next;       
};

list *reserve1(list *head)
{
   list *p1,*p2,*p3;  
   
  if(head==NULL || head->next==NULL)
  {
    return head;              
  }   
  p1 = head;
  p2 = head->next;
  
  while(p2!=NULL)
  {
     p3 = p2->next;
     
     p2->next = p1;
     
     p1 =p2;
     
     p2 =p3; 
                 
  }
  
  head ->next= NULL;
  
  head = p1;
  return head;
}

list *reserve2(list *head,list *pre)
{
     list *p=head->next;
     head->next=pre;
    // printf("*\n");
     if(p==NULL)
     {
         return head;          
     }
     else
     {
        return reserve2(p,head); 
     }
}

int main()
{
    
    list *a[5];
    
    for(int i=0;i<5;i++)
    {
      a[i] = new list;
      a[i]->data = i;
      a[i]->next=NULL;                
    } 
    
    a[0]->next = a[1];
    a[1]->next = a[2];
    a[2]->next = a[3];
    a[3]->next = a[4];
    list *root;
    root = a[0];
    
    while(root!=NULL)
    {
       printf("%d->",root->data);
       root = root->next;           
    }
    
    printf("\n");
    root = a[0];
    
    root=reserve2(root,NULL);
    while(root!=NULL)
    {
       printf("%d->",root->data);
       root = root->next;           
    }
    
    /*
    root = a[0];
    root=reserve1(root);
    
    while(root!=NULL)
    {
       printf("%d->",root->data);
       root = root->next;           
    }
    */
   //for(;;);
return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值