单链表的倒置_C语言

思想为:head指针不断后移,指针反向即可,代码为:

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


typedef struct node
{
      int data;
      struct node *next;
}node,*LinkList;


void creat(LinkList &L)
{
    node *p,*q;
    L=(LinkList)malloc(sizeof(node));
    if (L==NULL)
    {
        exit(0);
    }
    L->next=NULL;
    L->data=0;
 
   p=L;
   for(int i=5;i>0;i--)
   {
       q=(LinkList)malloc(sizeof(node));
       printf("Input :");
       scanf("%d",&(q->data));
       q->next=NULL;
       p->next=q;
       p=q;
    } 
}

void ListReverse(LinkList &L)
{
     node * head=L;
     if(head!=NULL&&head->next!=NULL)
    {
        node *p=head;
        node *q=head->next;
        p->next=NULL;
        while(q->next!=NULL)
       {
             head=q->next;
             q->next=p;
             p=q;
            q=head;
       }
  
       head->next=p;
       L=head;
    }
 
}

void main()

      LinkList L;
     //初始化
     creat(L);
    //倒置
     ListReverse(L);
     //显示
     LinkList p;
     p=L;
     while(p->next!=NULL)
     {
          printf("%d   ",p->data);
          p=p->next;
     } 
}

经过测试,完全正确!

原文地址:https://www.cnblogs.com/alexzp/p/2293281.html