Function to get Nth Node in LL

From beginning of the list:
#include<stdio.h>
#include<stdlib.h>
struct node
{
    int data;
    struct node* next;
};
int main()
{
    struct node* head = NULL;
    push(&head,8);
    push(&head,7);
    push(&head,3);
    push(&head,4);
    push(&head,1);
    printf("LinkedList:\n");
    print(head);
    int value = GetNth(head,0);
    printf("\nValue of Nth node is: %d",value);
    return 0;
}
void push(struct node** ref, int newData)
{
    struct node* newNode = (struct node*)malloc(sizeof(struct node));
    newNode->data = newData;
    newNode->next = (*ref);
    (*ref) = newNode;
}
int GetNth(struct node* head, int index)
{
    struct node* current = head;
    int count =0;
    while(current != NULL)
    {
    if(count == index)
    {
    return(current->data);
    }
    count++;
    current = current ->next;
    }
}
void print(struct node* n)
{
    while(n!= NULL)
    {
    printf("%d",n->data);
    n= n->next;
    }
}

Output:
LinkedList:
14378
Value of Nth node is: 1

From end of the list:
int GetNth(struct node* head, int index)
{
    struct node* p = head;
    struct node* q = head;
    int count =0;
    while(count < index)
    {
    count++;
    q=q->next;
    }
    while(q!= NULL)
    {
    p=p->next;
    q=q->next;
    }
    return (p->data);

}

Output:
LinkedList:
87654321
Value of Nth node is: 1

Comments

Popular posts from this blog

Three mislabeled Jar

Difference between Macro And function