1-2 链表逆置 (20 分)

1-2 链表逆置 (20 分)
本题要求实现一个函数,将给定单向链表逆置,即表头置为表尾,表尾置为表头。链表结点定义如下:

struct ListNode {
int data;
struct ListNode *next;
};
函数接口定义:
struct ListNode *reverse( struct ListNode *head );
其中head是用户传入的链表的头指针;函数reverse将链表head逆置,并返回结果链表的头指针。

裁判测试程序样例:
#include <stdio.h>
#include <stdlib.h>

struct ListNode {
int data;
struct ListNode *next;
};

struct ListNode *createlist(); /裁判实现,细节不表/
struct ListNode *reverse( struct ListNode *head );
void printlist( struct ListNode *head )
{
struct ListNode *p = head;
while § {
printf("%d “, p->data);
p = p->next;
}
printf(”\n");
}

int main()
{
struct ListNode *head;

head = createlist();
head = reverse(head);
printlist(head);

return 0;

}

/* 你的代码将被嵌在这里 */
输入样例:
1 2 3 4 5 6 -1
结尾无空行
输出样例:
6 5 4 3 2 1

#include<stdio.h>
#include<stdlib.h>
 struct ListNode
{
    int data;
    struct ListNode*next;
};
 struct ListNode *createlist();
 struct ListNode *reverse( struct ListNode *head);
 struct ListNode *createlist()
{
    struct ListNode *L=NULL;
    struct ListNode *s,*r=NULL;
    int x;
    scanf("%d",&x);
    while(x!=-1)
    {
        s=(struct ListNode*)malloc(sizeof(struct ListNode));
            s->data=x;
            if(L==NULL)L=s;
            else r->next=s;
            r=s;
            scanf("%d",&x);
    }
    if(r!=NULL) r->next=NULL;
    return L;
};
 struct ListNode *reverse( struct ListNode *head)
{
    struct ListNode *p,*q;
    p=head;
    head=NULL;
    while(p)
    {
        q=p;
        p=p->next;
        q->next=head;
        head=q;
    }
    return head;
}
void printlist( struct ListNode *head)
{
    struct ListNode *p=head;
    while(p)
    {
        printf("%d",p->data);
        p=p->next;
    }
    printf("\n");
}
int main()
{
     struct ListNode *head;
    head=createlist();
    head=reverse(head);
    printlist(head);
    return 0;
}

1.注意链表有没有头节点
2.尾插法是顺的,头插法是逆的

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值