Commit 749998c9 authored by Liam E. Roeth's avatar Liam E. Roeth

Update llist.c

parent b730c2ff
#include<stdio.h>
#include<stdlib.h>
#include "llist.h"
void print_node(NODE *head, int pos){
NODE *currentNode;
currentNode = head;
for (int i = 0; i<pos; i++){
currentNode = currentNode->next;
}
printf("The data at index %d is: %d", pos, currentNode->data);
}
void print_list(NODE *head){
printf("Printing list...\n");
NODE *currentNode;
currentNode = head;
int i = 0;
while (currentNode->data != NULL){
printf("Index: %d; Data: %d\n",i,currentNode->data);
currentNode=currentNode->next;
i++;
}
}
NODE* search(int n, NODE *head){
printf("Searching list for: %d", n);
NODE *currentNode;
currentNode = head;
while (currentNode->data != NULL){
if(currentNode->data == n){
printf("Location found, index: %d.", currentNode);
return currentNode;
}
currentNode=currentNode->next;
}
printf("Not found in this list.");
}
NODE *construct(datatype data, NODE *next){
NODE *out = malloc(sizeof(NODE));
if(out != NULL){
out->data = data;
out->next = next;
}
return out;
}
NODE *traverse(NODE *head, int pos){
if(head==NULL)
return NULL;
int i;
for(i=0;i<pos || pos<0;i++){
if(head->next != NULL)
head = head->next;
else
break;
}
return head;
}
int delete_node_after(NODE *head){
if(head==NULL || head->next == NULL)
return 1;
NODE* tmp = head->next;
head->next = head->next->next;
free(tmp);
return 0;
}
NODE *construct_list(datatype list[], int size){
if(size<=0)
return NULL;
NODE *next = construct(list[size-1],NULL);
NODE *head;
int i;
for(i=size-2;i>=0;i--){
head = next;
next = construct(list[i],head);
if(next == NULL)
Delete_List(head);
}
return next;
}
int add_to_end(NODE *head, datatype new_data){
return Insert_Node(head, -1, new_data);
}
int Insert_Node(NODE *head, int pos, datatype new_data){
if(head==NULL)
return 1;
if(pos!=0)
return Insert_Node_After(traverse(head,pos-1),new_data);
else{
int out = Insert_Node_After(head,head->data);
if(out>0)
return out;
head->data = new_data;
}
return 0;
}
int Insert_Node_After(NODE *head, datatype data){
if(head==NULL)
return 1;
NODE *new = construct(data, head->next);
if(new == NULL)
return 2;
head->next = new;
return 0;
}
int Length(NODE *head){
if(head==NULL)
return 0;
int i=1;
while((head=head->next) != NULL)
i++;
return i;
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment