以下代码不会打印显示下面链表中最大元素的最后一行。
在下面的代码中,我对链表求和,打印整个链表,打印链表的长度,并希望打印链表中找到的最大值。
由于某种原因,编译器不会打印最后一行。
#include <iostream>
#include <stdio.h>
using namespace std;
struct Node{ //if you want to convert to class, you need to assign access specifiers to public since they're private on default
int data;
struct Node *next;
}*first = NULL;
void create(int A[], int n)
{
struct Node *t; //create a temporary pointer t
struct Node *last; //pointer, points to the last node - helps me add a new node at the END of a linked list
//as of now, the linked list is empty, so we must create the first node!
first = new Node;//create new node on the heap, and first will be pointing on that new node
first -> data = A[0]; // Assign first the first element on the array
first -> next = NULL;//Should point to a null value as it is the only element on the list to start/currently
last = first; //last points on first node
for (int i = 1; i <n; i++)// i starts at element 1 since first has been assigned the 1st element in the array
{
t = new Node; //create a new node
t->data = A[i]; //fill up the data of t from A[i] which will be iterated through and assigned to data
t->next = NULL; // the next node should be pointing to NULL, as there is nothing at the moment when the iteration begins that it is initially pointing to
last -> next = t;
last = t;
}
}
int length (struct Node *p)
{
int l = 0;
while (p)
{
l++;
p = p->next;
}
return l;
}
int sum (struct Node *p){
int s= 0;
while(p){
s+=p->data;
p = p->next;
}
return s;
}
int max (struct Node *p){
int max = -32767;
while(p){
if(p->data > max){
max = p->data;
p = p->next;
}
}
return max;
}
void display (struct Node *p)
{
while (p != 0 )
{
cout<<p->data<<" ";
cout<<p->next<<" ";
p = p->next;
}
}
int main() {
int A [] = {1,2,3,18,5, 6, 7};
create (A,7);
display(first);
cout<<endl;
cout<<"The length of the linked list (the number of nodes) is: "<< length(first)<<endl;
cout<<"The sum of the linked list values (nodes) is: "<< sum(first)<<endl;
cout<<"The maximum value in the linked list (of the nodes) is: "<< max(first)<<endl;
return 0;
}
我做错了什么?
你的max
函数有一点问题,你的函数永远不会遍历整个列表,因为你把p = p->next
放在if
块内,你必须按如下方式编辑它
int max (struct Node *p){
int max = -32767;
while(p !=nullptr ){
if(p->data > max){
max = p->data;
}
p = p->next;
}
return max;
}
正因为如此,您将p = p->next
放在最大检查范围内,因此,如果max
设置为18
,则无法指向列表的next
,因为列表中没有任何大于18
的数据,因此列表永远不会完成,您的迭代器将在固定点停止,while 循环将永远运行!!
max()
函数不会像其他函数那样在每次迭代时递增节点指针。如果它遇到不大于当前max
的data
值,那么它就会陷入无限循环。
您需要将迭代移出内部if
块:
int max (struct Node *p){
int m = -1;
while (p){
if (p->data > max){
max = p->data;
}
p = p->next;
}
return m;
}