遍历并确定长度为n的单链表中值最大的结点


#include <stdio.h>
#include <stdlib.h>

typedef int DataType;
typedef struct Node
{
    DataType data;
    struct Node* next;
}Node;

//建立一个带头结点的空链表
Node *InitList(Node *first)
{
	first=(Node *)malloc(sizeof(Node));
	first->next=NULL;
	return first;
}
//遍历单链表,请把代码补全
void PrintList(Node *first)
{
	Node *p;
	p=first->next;
	while(p)
	{
		printf("%d ",p->data);
		p=p->next;
	}
	printf("\n");
}
/*本函数的功能是在头结点后面插入一个新结点,结点的数据域的值为x*/
void InsertAtHead(Node *first,DataType x)
{
	Node *T;
	T = (Node *)malloc(sizeof(Node));
	T->data = x;
	T->next = first->next;
    first->next = T;
}

int Max(Node *L){
	Node *pmax;
	pmax = (Node *)malloc(sizeof(Node));
	Node *p;
	p = (Node *)malloc(sizeof(Node));
	if(L->next == NULL) return NULL;
	pmax = L->next;
	p = L->next->next;
	
	while(p != NULL){
		if(p->data > pmax->data) p = pmax;
		p = p->next;
	}
	printf("%d\n",pmax->data);
	
	
}

int main()
{
	Node *first; 
    first=InitList(first);
    InsertAtHead(first,2);
    PrintList(first);
    InsertAtHead(first,4);
    InsertAtHead(first,34);
    InsertAtHead(first,42);
    InsertAtHead(first,45);
    Max(first);
    
    PrintList(first);
}
posted @ 2022-04-26 17:00  晓梦ペ  阅读(233)  评论(0)    收藏  举报