cs161examples/cs161BW8/listStructStr.cpp

66 lines
989 B
C++

#include <iostream>
using namespace std;
/*
Goal:
Implement lists not with arrays but with
structs that contain pointers
commonly called linked lists
|1| -> |2| -> |5| -> |6| -> nullptr
*/
// bad definition leads to size
// equation of the form
// size(struct) = size(struct) + 1
// good definition leads to size equation
// of the form
// size(struct) = 1 + 1
struct Node {
int data;
Node* next;
};
Node* makeNode(int v){
Node* n = new Node;
n->data = v;
n->next = nullptr;
return n;
}
// revist this when we add deletion
void append(Node* lst, int v){
if(lst->next == nullptr){
Node* n = makeNode(v);
lst->next = n;
}
else{
append(lst->next,v);
}
}
void printList(Node* lst){
if(lst != nullptr){
cout << lst->data << " ";
printList(lst->next);
}
else{
cout << endl;
}
}
int main(){
Node* ourList = makeNode(0);
append(ourList,1);
append(ourList,2);
append(ourList,3);
printList(ourList);
return 0;
}