LinkedList
it was a short practice for exam not hard at allunknown
c_cpp
4 years ago
2.6 kB
14
Indexable
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
struct node* next;
int data;
}node;
typedef struct linkedList{
node* head;
node* tail;
} linkedList;
typedef struct graph
{
linkedList* bonds[3];
} graph;
node* newNode(int val)
{
node* newNode = malloc(sizeof(node*));
newNode->data = val;
newNode->next = NULL;
return newNode;
}
linkedList* insertAtHead(linkedList* myList, int val)
{
node* temp = newNode(val);
if(myList->tail == NULL)
{
myList->tail = temp;
}
temp->next = myList->head;
myList->head = temp;
return myList;
}
linkedList* insertAtTail(linkedList* myList, int val)
{
node* temp = newNode(val);
if(myList->tail == NULL)
{
insertAtHead(myList, val);
return myList;
}
(myList->tail)->next = temp;
myList->tail = temp;
return myList;
}
linkedList* deleteAtTail(linkedList* myList)
{
if(myList->head == NULL)
{
return myList;
}
node* pivot = myList->head;
while(pivot->next != myList->tail)
{
pivot = pivot->next;
}
pivot->next = NULL;
printf("\n___Tail Deleted: (%d)___", (myList->tail)->data);
myList->tail = pivot;
return myList;
}
linkedList* deleteAtHead(linkedList* myList)
{
if(myList->head == NULL)
{
return myList;
}
printf("\n___Head deleted: (%d)___\n", (myList->head)->data);
myList->head = (myList->head)->next;
return myList;
}
void printList(linkedList* myList)
{
node* pivot = myList->head;
int counter = 0;
while(pivot != NULL)
{
printf("\nList[%d] = (%d)\n", counter, pivot->data);
pivot = pivot->next;
counter++;
}
}
int main()
{
linkedList* bond_1 = malloc(sizeof(linkedList*));
linkedList* bond_2 = malloc(sizeof(linkedList*));
linkedList* bond_3 = malloc(sizeof(linkedList*));
for(int i = 0, j = 4, k = 10; i < 4; i++, j--, k--)
{
bond_1 = insertAtHead(bond_1, i);
bond_2 = insertAtHead(bond_2, j);
bond_3 = insertAtHead(bond_3, k);
}
graph* myGraph = malloc(sizeof(graph*));
myGraph->bonds[0] = bond_1;
myGraph->bonds[1] = bond_2;
myGraph->bonds[2] = bond_3;
printf("\n-------------1------------\n");
printList(myGraph->bonds[0]);
printf("\n-------------2------------\n");
printList(myGraph->bonds[1]);
printf("\n-------------3------------\n");
printList(myGraph->bonds[2]);
return 0;
}Editor is loading...