zoukankan      html  css  js  c++  java
  • YTU 2991: 链表节点逆置(线性表)

    2991: 链表节点逆置(线性表)

    时间限制: 1 Sec  内存限制: 128 MB
    提交: 14  解决: 6

    题目描述

    设计一个算法,将一个带头节点的数据域依次为a1,a2,…,an(n>=3)的单链表的所有节点逆置,即第一个节点的数据域变为an,……,最后一个节点的数据域变为a1,请尽量采用较优算法,时间复杂度为O(n)最佳!

    线性表的定义为
    typedef struct Node
    {
        ElemType data;
        struct Node *next;
    } SqList;
     
    需编写的算法为
    SqList *Deal(SqList *p);
     


    注意:只需提交你所编写的算法

    输入

    输入的第一行包含一个整数,代表单链表的长度。接下来的一行是链表每个节点的数据域的值。

    输出

    输出包含一行,即逆置节点后链表的每个节点的数值。

    样例输入

    10
    1 2 3 4 5 6 7 8 9 10

    样例输出

    10 9 8 7 6 5 4 3 2 1
    

    提示

    迷失在幽谷中的鸟儿,独自飞翔在这偌大的天地间,却不知自己该飞往何方……

    #include <stdio.h>
    #include <stdlib.h>
    typedef int ElemType;
    typedef struct Node
    {
        ElemType data;
        struct Node *next;
    } SqList;
    SqList *Init(int n)
    {
        if(n<3)exit(-1);
        SqList *head=NULL,*p1,*p2;
        head=(SqList*)malloc(sizeof(SqList));
        p1=p2=(SqList*)malloc(sizeof(SqList));
        for(int i=0; i<n; i++)
        {
            if(i==0)head->next=p1;
            else p2->next=p1;
            scanf("%d",&p1->data);
            p2=p1;
            p1=(SqList*)malloc(sizeof(SqList));
        }
        p2->next=NULL;
        return head;
    }
    void Print(SqList *p)
    {
        p=p->next;
        while(p->next!=NULL)
        {
            printf("%d ",p->data);
            p=p->next;
        }
        printf("%d
    ",p->data);
    }
    SqList *Deal(SqList *p)
    {
        SqList *a=p->next,*b=p->next->next,*c=p->next->next->next,*head=p;
        while(true)
        {
            if(a==p->next)a->next=NULL;
            b->next=a;
            if(c->next==NULL)
            {
                c->next=b;
                break;
            }
            a=b,b=c,c=c->next;
        }
        head->next=c;
        return head;
    }
    int main()
    {
        int n;
        SqList *head=NULL;
        scanf("%d",&n);
        head=Init(n);
        head=Deal(head);
        Print(head);
        return 0;
    }
    


  • 相关阅读:
    Unity中的欧拉旋转
    Unity-Rigidbody碰撞穿透
    C#实现单例模式的几种方法
    C#OO初级思想
    C#虚方法virtual
    数据库查询
    DNS 域名服务器搭建
    iptables 基本操作
    通过adb 操作手机
    linux 调整逻辑卷空间大小
  • 原文地址:https://www.cnblogs.com/im0qianqian/p/5989385.html
Copyright © 2011-2022 走看看