[英]how to add value to every second node in the list
我嘗試遍歷值的鏈接列表,並將一些給定值添加到列表中的每個其他節點。 它應該總是開始添加到列表中的第一個節點,然后從那里添加到每個其他節點。
錯誤是程序沒有給出任何 output 但它很可能是 function 有問題
這是我嘗試過的:
#include <iostream>
using namespace std;
// Declare the Node structure to be used for the linked list.
// Each node should have an int for data, and
// a pointer to the next node.
struct Node {
int data;
Node *pNext;
};
// Displays the list number values
void display( Node *pTemp){
while( pTemp != NULL) {
cout << pTemp->data << "->";
pTemp = pTemp->pNext;
}
cout << endl;
}
// Create a new node, put the userInput number in it, and APPEND
// it to the END of the list.
void append(Node* &pHead, int userInput) {
Node *pTemp = new Node;
pTemp->data = userInput;
pTemp->pNext = NULL;
Node *pLast = pHead;
// Find the last node on the list
while(pLast != NULL && pLast->pNext != NULL) {
pLast = pLast->pNext;
}
if( pLast == NULL) {
// Make this new node the first node on an otherwise empty list
pHead = pTemp;
}
else {
// Append this new node to the end of the existing list
pLast->pNext = pTemp;
}
}
//-----------------------------------------------------------------------
// *** Do not change anything above this point. ***
//------------------------------------------------------------------------
// add valueToAdd to every second node in the list
void addEveryOther(Node* &pHead, int valueToAdd) {
// while there is a node after pTemp->pNext
while(pHead->pNext != NULL || pHead != NULL) {
// add valueToAdd to pTemp->data
pHead->data += valueToAdd;
// move pTemp to the next node
pHead = pHead->pNext->pNext;
}
}
//-----------------------------------------------------------------------
// *** Do not change anything below this point. ***
//------------------------------------------------------------------------
int main() {
int userInput;
Node *pHead = NULL; // pointer to the head of the list
int value;
// Create the linked list
cout << "Enter list numbers separated by space, followed by -1: ";
cin >> userInput;
// Keep looping and appending nodes on the list until
// end-of-input flag of -1 is given
while(userInput != -1) {
// Store this number on the list
append(pHead, userInput);
cin >> userInput;
}
cout << "Enter value to add on: ";
cin >> value;
addEveryOther(pHead, value);
display(pHead);
return 0;
}// end main()
這是輸入:
2 8 9 5 11 3 6 -1
Enter value to add on: 5
預計 output:
7->8->14->5->16->3->11
您需要考慮做事的順序。 以及您的條件中的邏輯。
在條件pHead->pNext != NULL || pHead != NULL
pHead->pNext != NULL || pHead != NULL
在檢查它是否為 null 指針之前,您將取消引用pHead
。
您需要以相反的順序進行檢查,並使用邏輯 AND 代替: pHead != NULL && pHead->pNext != NULL
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.