Chinaunix首页 | 论坛 | 博客
  • 博客访问: 516328
  • 博文数量: 118
  • 博客积分: 10028
  • 博客等级: 上将
  • 技术积分: 1820
  • 用 户 组: 普通用户
  • 注册时间: 2007-11-07 18:46
文章分类

全部博文(118)

文章存档

2009年(12)

2008年(106)

我的朋友

分类: C/C++

2008-11-08 17:59:29


我有点傻,本来开始就正确了的,因为只有一个输出最后结果,而没有输出原始的链表,输出的顺序和输入的顺序相同,我就纳闷了,认真仔细的研究了reverse()函数,应该是对的阿~ 后面改了下,加上输出原始链表,结果顺序与输入相反......哎,问题解决了。原来是插入的时候就和输入反序了的~呵呵

基本思想:
   一次类似插入操作的变换,用一个新的头指针(不好讲,慢慢体会吧)


代码:

#include <stdio.h>
#include <stdlib.h>

#define N 5

typedef int KeyType;

struct record{
    KeyType key;
    struct record *next;
};
typedef struct record Record;

/* Insert a record into list */
void insert_list(KeyType x,Record **head)
{
    Record *r;// a temp record


    r=(Record *)malloc(sizeof(Record));
    if(r == NULL){
        printf("error \n");
        exit(1);
    }
    r->key=x;
    r->next=NULL;

    if(*head != NULL)
        r->next=*head;

    *head=r;
}

/* Reverse the list */
Record *reverse(Record *head)
{
    Record *r,*newhead=NULL;
    Record *p;

    p=head; //use p to traverse the old list

    while(p != NULL)
    {
        r=p; //'r' point to each node

        p=r->next;
        r->next=newhead;
        newhead=r;
    }

    return newhead;
}

int main(int argc,char **argv)
{
    int i,x;
    Record *p;
    Record *head=NULL,*newhead=NULL;

    printf("Input %d number:\n",N);
    for(i=0;i<N;i++)
    {
        scanf("%d",&x);
        insert_list(x,&head);
    }

    printf("Before reverse:");
    p=head;
    while(p != NULL)    
    {
        printf("%d ",p->key);    
        p=p->next;
    }
    printf("\n");

    newhead=reverse(head);

    printf("After reversed:");
    p=newhead;
    while(p != NULL)    
    {
        printf("%d ",p->key);    
        p=p->next;
    }
    printf("\n");
    
    return 0;
}

阅读(1522) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~