设单链表的数据为互不相等的整数,建立一个单链表,并设计一个算法,找出单链表中元素值最大 的结点。

设单链表的数据为互不相等的整数,建立一个单链表,并设计一个算法,找出单链表中元素值最大的结点。

  要求:

1)单链表的数据从键盘输入;

2)输出单链表所有结点的数据和最大值结点序号

#include "iostream"
using namespace std;
#include "malloc.h"
#include "stdio.h"
#define N 10
typedef int ElemType;
typedef struct LNode
{
    ElemType  data;
    struct LNode  *next;
}LNode, *LinkList;

int MaxNode(LinkList h)
{
    int j, k;
    LNode *p, *q;
    if (h->next == NULL) return 0;
    q = h->next;   p = q->next;
    k = 1; j = 2;
    while (p != NULL)
    {
        if (p->data>q->data) { q = p; k = j; }
        p = p->next; j++;
    }
    return k;
}//MaxNode
int output(LinkList h)
{
    LNode *q;
    if (h->next == NULL) return 0;
    q = h->next;
    while (q != NULL)
    {
        cout << q->data << " ";
        q = q->next;
    }
}
void CreateLink(LinkList &h, ElemType a[], int n)
{
    LNode *s, *r; int i;
    h = (LNode *)malloc(sizeof(LNode));
    r = h;
    for (i = 0; i < n; i++)
    {
        s = (LNode *)malloc(sizeof(LNode));
        s->data = a[i];
        r->next = s; r = s;
    }
    r->next = NULL;
}


void main()
{
    LinkList head;
    ElemType a[N];
    int i, k;
    cout << "请输入一组数:" << endl;
    for (i = 0; i<N; i++) scanf_s("%d", &a[i]);
    CreateLink(head, a, N);
    cout << "所有数据:" << endl;
    output(head);
    cout <<endl << "最大值节点序号:" << endl;
    k = MaxNode(head);
    cout << k << "  "; cout << endl;
}

 

欢迎访问我的博客https://www.ndmiao.cn/

 

posted @ 2019-03-31 17:31  南岛鹋  阅读(697)  评论(0编辑  收藏  举报