Daftar c
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *nextPtr;
};
//create a node
struct Node *newNode(int data)
{
struct Node *out;
//malloc allocates dinamically what's inside the round brackets
out = (struct Node *)malloc(sizeof(struct Node));
//-> its the equivalent of (*out).data = data
//all'inerno della variabile data della struttura out metti data
out->data = data;
out->nextPtr = NULL;
return out;
}
////////////////////////////////////////////////////////////////
//get the list length
int len(struct Node *list)
{
int out = 0;
while (list != NULL)
{
out++;
list = list->nextPtr;
}
return out;
}
////////////////////////////////////////////////////////////////
//get last node
struct Node *getLastNode(struct Node *list)
{
struct Node *currentNode;
if (list == NULL)
currentNode = NULL;
else
{
currentNode = list;
while (currentNode->nextPtr != NULL)
{
currentNode = currentNode->nextPtr;
}
}
return currentNode;
}
////////////////////////////////////////////////////////////////
//pop cut the Node from the list, but the node exist anyway, if you have to put that Node in another list then it should be useful
struct Node *pop(struct Node **listPtr)
{
struct Node *out, *box;
int n = len(*listPtr);
int idx = 0;
switch (n)
{
case 0:
out = NULL;
break;
case 1:
out = *listPtr;
*listPtr = NULL;
break;
default:
idx = 0;
box = *listPtr;
//i have to go at the last but one node and cut that
while (idx < n - 2)
{
box = box->nextPtr;
}
out = box->nextPtr;
box->nextPtr = NULL;
}
return out;
}
////////////////////////////////////////////////////////////////
struct Node *add(struct Node **listPtr, int data)
{
//create the node to add
struct Node *toAdd = newNode(data);
if (*listPtr == NULL)
{
*listPtr = toAdd;
}
//add the node TO THE END OF THE LIST
else
{
(getLastNode(*listPtr))->nextPtr = toAdd;
}
return toAdd;
}
int main()
{
struct Node *list = NULL;
printf("Size %d\n", len(list));
add(&list, 123);
printf("Size %d\n", len(list));
printf("LastNode %d\n\n", (getLastNode(list))->data);
add(&list, 12);
printf("Size %d\n", len(list));
printf("LastNode %d\n\n", (getLastNode(list))->data);
// VISIT the list
struct Node *currNodePtr;
currNodePtr = list;
while (currNodePtr != NULL)
{
printf("data = %d\n", currNodePtr->data);
currNodePtr = currNodePtr->nextPtr;
}
pop(&list);
printf("Size %d\n", len(list));
printf("LastNode %d\n\n", (getLastNode(list))->data);
pop(&list);
printf("Size %d\n", len(list));
return 0;
}
The Bad Programmer