您的位置:首页 > 其它

华为机试—逆序链表输出

2015-01-09 23:55 183 查看
题目描述:

将输入的一个单向链表,逆序后输出链表中的值。链表定义如下:

typedef struct tagListNode

{

int value;

struct tagListNode *next;

}ListNode;



要求实现函数:

void converse(ListNode **head);

【输入】head: 链表头节点,空间已经开辟好

【输出】head: 逆序后的链表头节点

【返回】无

【注意】只需要完成该函数功能算法,中间不需要有任何IO 的输入输出

#include<iostream>
typedef struct tagListNode
{
      int value;
      struct tagListNode *next;
}ListNode;
void print(ListNode **head)
{
    ListNode *f=(*head)->next;
    while(f)
    {
        printf("%d\n",f->value);
        f=f->next;
    }
}
void converse(ListNode **head)
{
    ListNode *f=(*head)->next;
    ListNode* pre=NULL;
    ListNode *s;
    while(f){
        s=f->next;
        f->next=pre;
        pre=f;
        f=s;
    }
    (*head)->next=pre;
}
int main(int argc, char *argv[])
{
    ListNode *h=(ListNode*)malloc(sizeof(ListNode));
    h->next=NULL;
    for(int i=0;i<10;++i)
    {
        ListNode *tmp=(ListNode*)malloc(sizeof(ListNode));
        tmp->value=i;
        tmp->next=h->next;
        h->next=tmp;
    }
    print(&h);
    converse(&h);
    printf("\n");
    print(&h);
    return 0;
}


测试结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: