#include <stdio.h>
#include <stdlib.h>
#include "node.h"
struct node* CreateNode() {
return malloc(sizeof(struct node));
}
void PrintList(struct node* head) {
struct node* current = head;
while(current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("NULL\n");
}
struct node* InsertInFront(struct node* head, int value) {
struct node* newNode = CreateNode();
newNode->data = value;
newNode->next = head;
return newNode;
}
struct node* CreateList(int values[], int len) {
// check for empty list
if (len == 0) return NULL;
struct node* head = NULL;
int i;
for(i=len; i>0; i--) {
head = InsertInFront(head, values[i-1]);
}
return head;
}
int LinkedListLength(struct node* head) {
struct node *temp = head;
int i = 0;
while(temp != NULL){
temp = temp -> next;
i++;
}
return i;
}
struct node* InsertAtEnd(struct node* head, int value) {
struct node *temp = head;
int i = 1;
struct node *newNode;
while (temp != NULL){
if(temp -> next == NULL){
newNode = CreateNode();
newNode -> data = value;
newNode -> next = NULL;
return head;
}
temp = temp -> next;
i++;
}
return head;
}
struct node* InsertAtN(struct node* head, int value, int N) {
int i = 1;
struct node *temp = head;
if(N > LinkedListLength(head)){
printf("ERROR: Node <N> does not exist");
}
if(N == 0){
InsertInFront(head, value);
}
struct node *newNode;
while (i <= N){
if(i == N){
newNode = CreateNode();
newNode -> data = value;
newNode -> next = temp -> next;
temp = newNode;
return head;
}
temp = temp -> next;
i++;
}
return head;
}
struct node* DeleteNode(struct node* head, int pos) {
struct node *temp = head;
if(pos > LinkedListLength(head)){
printf("ERROR: Node does not exist");
}
int i = 1;
struct node *newNode;
while(i < pos){
if(i+1 == pos){
temp = temp -> next -> next;
free(temp -> next);
return head;
}
temp = temp -> next;
i++;
}
return newNode;
}
No comments:
Post a Comment