首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

【简单有关问题】链表逆转

2012-04-26 
【简单问题】链表逆转C/C++ code#includestdio.h#includestdlib.htypedef struct student{int datastru

【简单问题】链表逆转

C/C++ code
#include<stdio.h>#include<stdlib.h>typedef struct student{    int data;    struct student* next;} node;node* LinklistCreat(int n){    node*head,*p,*s;    int i;    head=NULL;    printf("请输入相关数据:\n");    for(i=1;i<=n;i++)    {        p=(node*)malloc(sizeof(node));        scanf("%d",&(p->data));        //p=(node*)malloc(sizeof(node));        p->next=NULL;        if(head==NULL)        head=p;        else s->next=p;        s=p;        }    return head;}void PrintList(node*head){    printf("链表输出为:\n");    node*p;    p=head;    while(p!=NULL)    {        printf("%d ",p->data);        p=p->next;    }    printf("\n");    }void INVERSE(node*head){    node *r,*q,*p;    p=head;    q=NULL;    r=NULL;    while(p!=NULL)    {        r=q;        q=p;        p=p->next;        q->next=r;    }    head=q;}int main(){    node*p;    int num,data,n;    printf("请输入要建立链表的长度:\n");    scanf("%d",&n);    p=LinklistCreat(n);//创建链表     PrintList(p);//输出链表         printf("链表逆转后为:\n");     INVERSE(p);//逆转链表    PrintList(p);        return 0;}

问题是链表逆转后只能输出原链表的第一位,请问原因在哪啊

[解决办法]
C/C++ code
//如果不用返回指针的方法,可考虑用二级指针或者引用node*  INVERSE(node*head){    node *r,*q,*p;    p=head;    q=NULL;    r=NULL;    while(p!=NULL)    {        r=q;        q=p;        p=p->next;        q->next=r;    }    head=q;    return head;}int main(){    node*p;    int num,data,n;    printf("请输入要建立链表的长度:\n");    scanf("%d",&n);    p=LinklistCreat(n);//创建链表     PrintList(p);//输出链表         printf("链表逆转后为:\n");     p=INVERSE(p);//逆转链表    PrintList(p);        return 0;}
[解决办法]
值传递,INVERSE(p);//逆转链表
不能改变p的值。p还是指向head

热点排行