数据结构(问题是:从单链表中查找出所有元素的最大值,该值由函数返回,若单链表为空,则显示错误并停止

1个回答

  • 同学你好,这是我帮你写 的代码

    在vc6.0中执行结果:

    希望你能采纳,如果想要C++写的直接hi我,有空发给你,

    # include

    # include

    # include

    typedef struct Node

    { int data; struct Node *pNext;}NODE, *PNODE;

    PNODE CreateLink(void);

    void TraveserLink(PNODE);bool MaxLink(PNODE, int *);

    int main(){ int val;//存放在大值 PNODE pHead = CreateLink();//创造单链表 TraveserLink(pHead);//遍历链表 if (MaxLink(pHead, val)) { printf("此链表的最大值是%d:n", val); } else { printf("此链表为空n"); }

    return 0;}PNODE CreateLink(void)

    { int len;//存放链表长度 printf("请输入链表长度len = "); scanf("%d", len);

    PNODE pHead = (PNODE)malloc(sizeof(NODE));//创造头结点

    if (pHead == NULL) { printf("动态内存分配失败!n"); exit(-1); }

    PNODE pTail = pHead; pTail->pNext = NULL; for (int i = 0; i < len; i++)

    { int val;//存放节点临时值 printf("请输入第%的个节点的值:", i+1); scanf("%d", val);

    PNODE pNew = (PNODE)malloc(sizeof(NODE));

    if (pNew == NULL) { printf("动态内存分配失败!n"); exit(-1); }

    pNew->data = val;

    pNew->pNext = NULL; pTail->pNext = pNew; pTail = pNew;

    } return pHead;}void TraveserLink(PNODE pHead)

    { PNODE p = pHead->pNext;

    while (p != NULL)

    { printf("%d ", p->data); p = p->pNext; } printf("n");}

    bool MaxLink(PNODE pHead, int *pVal)

    { PNODE q = pHead->pNext; if (NULL == q) { return false; } else { int k = q->data;//存放当前最大值 q = q->pNext; while (q != NULL) { if (k < q->data) { k = q->data; } q = q->pNext; } *pVal = k; return true; }}

相关问题