当前位置:编程学习 > C/C++ >>

单链表的逆置

单链表的逆置
 
 
#include<stdio.h>  
#include<stdlib.h>  
  
typedef struct node  
{  
    char data;  
    struct node *next;  
}node, *list;  
  
list TailCreat();                    //尾插法创建链表  
void Reverse(head);                  //逆置  
void print(head);                    //链表输出  
  
int main(void)  
{  
    list head;  
  
    head = TailCreat();              //尾插法创建链表  
    print(head);                     //链表输出  
    printf("\n");  
    Reverse(head);                   //逆置  
    print(head);                     //链表输出  
  
    return 0;  
}  
  
list TailCreat()                     //尾插法创建链表  
{  
    list head;  
    node *p, *w;  
    char c;  
    int flag = 1;  
  
    head = (node *)malloc(sizeof(node));  
    p = head;  
    p->next = NULL;  
  
    while(flag == 1)  
    {  
        printf("请输入数据:");  
        c = getchar();  
        flushall();  
        w = (node *)malloc(sizeof(node));  
        w->data = c;  
  
        if(c != '$')  
        {  
            p->next = w;  
            p= w;  
        }  
        else  
        {  
            flag = 0;  
            p->next = NULL;  
        }  
    }  
    return head;  
}  
  
void Reverse(list head)               //逆置  
{     
    node *p,*q;     
      
    p=head->next;     
    head->next=NULL;     
  
    while(p!=NULL)  
    {     
         q=p->next;     
         p->next=head->next;     
         head->next=p;     
         p=q;     
     }     
}     
  
void print(list head)                 //链表输出  
{  
    node *p;  
      
    for(p = head->next; p != NULL; p = p->next)  
        printf("%c ",p->data);  
}  

 

 
补充:软件开发 , C++ ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,