问题:(链表建立输出都正常)主函数调用子函数的结果,为什么这两种方法(一种int型调用,一种新建一个结构
体)都不输出有子函数的部分,但是这两种方法在其他此类型的代码中就能运行。
(补充:代码没有写出第一个为最大值的情况,因为不会写这种情况,如果您会写,感谢您的补充)
#include
#include
typedef int ElemType;
typedef struct Lnode
{
int data;
struct Lnode *next;
}LinkNode;
void InitList(LinkNode *&L)
{
L=(LinkNode *)malloc(sizeof(LinkNode));
L->next=L;
}
void CreatList(LinkNode *&L,int a[],int n)
{
LinkNode *p,*r=L;
for(int i=0;imalloc(sizeof(LinkNode));
p->data=a[i];
r->next=p;
r=p;
}
r->next=NULL;
}
void DispList(LinkNode *L)
{
LinkNode *p=L->next;
while(p!=L)
{
printf("%d ",p->data);
p=p->next;
}
}
int xh(LinkNode *L)
{
int i=0;
LinkNode *p=L->next;
int max=p->data;
while(p!=L&&p->data<=max)
{
i++;
p=p->next;
}
if(p->data>max)
{
i++;
}
return(i);
}
int main()
{
LinkNode *L;
int a[6];
InitList(L);
printf("请输入:");
for(int i=0;i<6;i++)
{
scanf("%d",&a[i]);
}
CreatList(L,a,6);
printf("请输出:");
DispList(L);
xh(L);
printf("\n最大的序号是%d",xh(L));
}
#include
#include
typedef int ElemType;
typedef struct Lnode
{
int data;
struct Lnode *next;
}LinkNode;
typedef struct
{
int i;
}xhreturn;
void InitList(LinkNode *&L)
{
L=(LinkNode *)malloc(sizeof(LinkNode));
L->next=L;
}
void CreatList(LinkNode *&L,int a[],int n)
{
LinkNode *p,*r=L;
for(int i=0;imalloc(sizeof(LinkNode));
p->data=a[i];
r->next=p;
r=p;
}
r->next=NULL;
}
void DispList(LinkNode *L)
{
LinkNode *p=L->next;
while(p!=L)
{
printf("%d ",p->data);
p=p->next;
}
}
xhreturn xh(LinkNode *L)
{
int i=0;
LinkNode *p=L->next;
int max=p->data;
while(p!=L&&p->data<=max)
{
i++;
p=p->next;
}
if(p->data>max)
{
i++;
}
xhreturn k;
k.i=i;
return(k);
}
int main()
{
LinkNode *L;
int a[6];
InitList(L);
printf("请输入:");
for(int i=0;i<6;i++)
{
scanf("%d",&a[i]);
}
CreatList(L,a,6);
printf("请输出:");
DispList(L);
xhreturn k=xh(L);
printf("\n最大的序号是%d",k.i);
}
**可以看一下这个 **
1、定义一个指针指向链表头部
2、定义一个变量,记录最大节点的逻辑序号
3、遍历整个链表
4、比较当前节点的值与记录的最大值,如果当前值更大,更新最大值的逻辑序号
5、重复步骤3和4,直到遍历完整个链表
6、返回最大值的逻辑序号
参考代码如下:
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
int index;
struct node *next;
};
int main(){
struct node *head, *p;
int max_index = 0;
int max_value = 0;
int i = 0;
// 构造链表
head = (struct node *)malloc(sizeof(struct node));
p = head;
for(i=0; i<10; i++){
p->data = i;
p->index = i;
p->next = (struct node *)malloc(sizeof(struct node));
p = p->next;
}
p->next = head; // 将最后一个节点的next指针指向head
// 遍历链表,查找最大节点
p = head;
do{
if(p->data > max_value){
max_value = p->data;
max_index = p->index;
}
p = p->next;
}while(p != head);
// 输出最大节点的逻辑序号
printf("The last max node's index is %d\n", max_index);
return 0;
}