初始化单链表,并在只遍历一次的情况下倒序

本文介绍了一种使用C语言实现单链表的方法,包括单链表的初始化及仅通过一次遍历实现链表元素的倒序。该方法适用于需要高效处理链表数据结构的应用场景。

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

/*
初始化单链表,并在只遍历一次的情况下倒序
*/


#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{
 int data;
 struct Node *next;
}node;
struct Node * nodeinit(void)                            //构建单链表
{
 node *head,*p,*q;
 head=(node*)malloc(sizeof node);
 int x=0,n=0;
 while(1)
 {
  printf("input the number:\n");
  scanf("%d",&x);
  if(x==0)
  {
   break;
  }
  else
  {
   p=(node *)malloc(sizeof node);
   p->data=x;
   if(++n==1)
   {
    head->next=p;  
   }
   else
   {
    q->next=p; 
   }

   q=p;
  }
 }
 p->next=NULL;
 return head;
}

void showlist(struct Node *head)                   //打印单链表
{
 printf("the list is:\n");
 struct Node *p=head->next;
 while(p!=NULL)
 {
  printf("%d\n",p->data);
  p=p->next;
 }
}

struct Node * resetlist(struct Node *head)   //单链表倒序
{
 printf("start reset!\n");
 struct Node *p,*q;
 p=head->next;
 while(p!=NULL)
 {
  q=p;
  p=p->next;
  q->next=head->next;
  if(q->next==q)
  {
   q->next=NULL;
  }
  head->next=q;
 }
 printf("success reset!\n");

 return head;
}


int main()
{
 struct Node *head1,*head2;
 
 head1=nodeinit();
 showlist(head1);

 head2=resetlist(head1);
 showlist(head2);

 return 0;
}

转载于:https://www.cnblogs.com/auleaf/archive/2011/11/24/2262396.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值