#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *nextPtr;
};
struct Node *newNode(int data)
{
struct Node *out;
out = (struct Node *)malloc(sizeof(struct Node));
out->data = data;
out->nextPtr = NULL;
return out;
}
int len(struct Node *list)
{
int out = 0;
while (list != NULL)
{
out++;
list = list->nextPtr;
}
return out;
}
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;
}
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;
while (idx < n - 2)
{
box = box->nextPtr;
}
out = box->nextPtr;
box->nextPtr = NULL;
}
return out;
}
struct Node *add(struct Node **listPtr, int data)
{
struct Node *toAdd = newNode(data);
if (*listPtr == NULL)
{
*listPtr = toAdd;
}
else
{
(getLastNode(*listPtr))->nextPtr = toAdd;
}
return toAdd;
}
int main()
{
struct Node *list = NULL;
printf("Size %d
", len(list));
add(&list, 123);
printf("Size %d
", len(list));
printf("LastNode %d
", (getLastNode(list))->data);
add(&list, 12);
printf("Size %d
", len(list));
printf("LastNode %d
", (getLastNode(list))->data);
struct Node *currNodePtr;
currNodePtr = list;
while (currNodePtr != NULL)
{
printf("data = %d
", currNodePtr->data);
currNodePtr = currNodePtr->nextPtr;
}
pop(&list);
printf("Size %d
", len(list));
printf("LastNode %d
", (getLastNode(list))->data);
pop(&list);
printf("Size %d
", len(list));
return 0;
}