C语言-数据结构-单链表倒置

来源:互联网 发布:java中的接口是什么 编辑:程序博客网 时间:2024/06/05 20:57
/*#include <stdio.h>
#include <stdlib.h>
//单链表倒置
typedef struct node
{
    int data;
    struct node *next;
}body;
body *table()
{
    int i,a;
    body *head,*p1,*p2;
    head=NULL;
    for(i=0;;i++)
    {
       p1=(body *)malloc(sizeof (body));
       scanf("%d",&a);
       p1->data=a;
       if(head==NULL)
       {
           head=p1;
           p2=p1;
       }
       else
       {
           p2->next=p1;
           p2=p1;
       }
       if(getchar=='\n')
        break;
    }
    p2->next=NULL;
    return head;
}
body *reverse(body *head)//倒置
{
    body *p,*s;
    if(head->next&&head->next->next)
    {
        p=head; //p为第一个节点
        s=p->next;  //s为第二个节点
        p->next=NULL; //第一个节点指针域为空
      while(s)
       {
        p = s; //p为第二节点
        s= s->next; //s为第三个节点
        p->next=head; //划线,第二节点指针域
        head=p; //head为第二个节点
       }
    }
    return head;
}
void input()
{
    body *p;
    p=table();
    p=reverse(p);
    while(p)
    {
        printf("%d ",p->data);
        p=p->next;
    }
}
int main()
{
    input();
    return 0;
}
*/


#include <stdio.h>
#include <stdlib.h>
struct LNode{
    int data;
    struct LNode *next;
};
//创建
struct LNode *create(int n){
    int i,a;
    struct LNode *head,*p1,*p2;
    head = NULL;
    for(i=n;i>0;i--){
        scanf("%d ",&a);
        p1 = (struct LNode*)malloc(sizeof(struct LNode));
        p1->data = a;
        if(head==NULL){
            head = p1;
            p2 = p1;
        }else{
            p2->next = p1;
            p2 = p1;
        }
    }
    p2->next = NULL;
    return head;
}
//倒置
struct LNode *reverse(struct LNode *head){
    struct LNode *p,*s;
    if(head->next&&head->next->next){
        p=head;//p为第一个节点
        s=p->next;//s为第二个节点
        p->next=NULL;//第一个节点指针域为空 断线
        while(s){
            p = s;//p为第二节点
            s = s->next;//s未第三个节点
            p->next=head;//划线,第二节点指向第一节点
            head = p;//head为第二节点
        }
    }
    return head;
}
int main()
{
    int n;
    struct LNode *q;
    scanf("%d",&n);
    q=create(n);
    q=reverse(q);//倒置
    while(q){
        printf("%d ",q->data);
        q = q->next;
    }
    return 0;
}
struct node *reverse(struct node *head)
{
    struct node *p,*s;
    if()
}
原创粉丝点击