首页新闻找找看学习计划

C语言中单向的链表反转

0
悬赏园豆:15 [已解决问题] 解决于 2015-09-30 10:54
node* reverse1(node * head)
{
node*p,*q,*r;
p = head;

q = head->next;

head->next = NULL; 
while(q){

r = q->next;

q->next = p;

p = q;

q = r;
}

head=p;
/* while(p)
{
printf("%d ",p->num);
p=p->next;
}*/
printf("\n");
return head;

}
漫漫codeing路的主页 漫漫codeing路 | 初学一级 | 园豆:11
提问于:2015-09-30 09:46
< >
分享
最佳答案
0
#include <stdio.h>
#include <stdlib.h>

typedef struct _node
{
        int data;
        struct _node *next;
} node;

node*
reverse1(node * head)
{
        node*p,*q,*r;

        if( head != NULL )
        {
                p = head;
                q = head->next;

                head->next = NULL;
                while(q){
                        r = q->next;
                        q->next = p;

                        p = q;
                        q = r;
                }

                head=p;
        }
        return head;
}

int
main( void )
{
        node *link = NULL;
        node *tmp = NULL;
        int i = 0;

        for( i = 0; i < 5; i++ )
        {
                tmp = malloc( sizeof( node ) );
                if( tmp == NULL )
                        return -1;

                tmp->data = i;
                tmp->next = link;
                link = tmp;
        }

        tmp = link;
        printf( "before reversal:\n" );
        while( tmp )
        {
                printf( "%d ", tmp->data );
                tmp = tmp->next;
        }
        putchar( '\n' );

        link = reverse1( link );
        printf( "after reversal:\n" );
        tmp = link;
        while( tmp )
        {
                printf( "%d ", tmp->data );
                tmp = tmp->next;
        }
        putchar( '\n' );

        return 0;
}

测了一下,应该可以使吧
收获园豆:15
请叫我头头哥 | 大侠五级 |园豆:9382 | 2015-09-30 10:39
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册