单链表逆转

参照:http://www.cnblogs.com/bluestorm/p/3167424.html

getche()接收换行时会解析成‘\r’

#include <stdio.h>
#include <stdlib.h>
struct list{
    char data;
    struct list *next;
}node;
struct list* input()
{
    //p作为新结点,q不断连接新结点,h作为首结点返回
    struct list *p,*q,*h = NULL;
    while(1)
    {
        //新创建一个结点
        p = (struct list*)malloc(sizeof(node));
        scanf("%c",&p->data);
        p->next = NULL;
        if(p->data == '\n')//此处不为'\r'
            break;
        if(h == NULL)
        {
            h = q = p;
        }
        else{
            q->next = p;
            q = p;
        }
    }
    return h;
}
void display(struct list* pfirst)
{
    struct list *p = pfirst;
    while(p)
    {
        putchar(p->data);
        p = p->next;
    }
    puts("");
}
//1借助辅助空间
//建立临时的新链表,将新结点指向其前驱结点实现逆转
//struct list* reverse(struct list* Afirst)
//{
//    struct list *p,*h = NULL,*first = Afirst;
//    while(first)
//    {
//        p = (struct list*)malloc(sizeof(node));
//        p->data = first->data;
//        if(h == NULL)//第一个结点
//        {
//            h = p;
//            h->next = NULL;
//        }
//        else{
//            p->next = h;
//            h = p;
//        }
//        first = first->next;
//    }
//    return h;
//}
//2.头尾互换,指针指向反转
struct list* reverse(struct list* Afirst)
{
    struct list *p,*q,*h,*listen;
    p = listen = Afirst;
    q = NULL;
    //使listen指向最后一个结点
    while(listen->next)
        listen = listen->next;
    //p所指的结点始终串接在listen后面,q所指的结点则接在p后面,h则记住p在串接前的下一个结点
    while(p != listen)
    {
        h = p->next;
        listen->next = p;
        if(q == NULL)
        {
            q = p;
            q->next = NULL;
        }
        else{
            p->next = q;        
            q = p;
        }
        p = h;
    }
    return listen;
}
int main()
{
    struct list *Afirst,*Bfirst;
    Afirst = input();
    puts("逆转前:");
    display(Afirst);
    Bfirst = reverse(Afirst);
    puts("逆转后:");
    display(Bfirst);
    return 0;

}

 

posted @ 2016-02-03 20:36  我在这儿  阅读(325)  评论(0编辑  收藏  举报