Last active
December 1, 2015 05:08
-
-
Save jitsceait/a310c91678fe14e95df4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
typedef struct Node { | |
int data; | |
struct Node * next; | |
} Node; | |
Node * createNode(int val){ | |
Node * temp = (Node *)malloc(sizeof(Node)); | |
if(temp){ | |
temp->data = val; | |
temp->next = NULL; | |
} | |
return temp; | |
} | |
/* This function inserts node at the head of linked list */ | |
void push(Node **headRef, int data){ | |
Node * newNode = createNode(data); | |
newNode->next = *headRef; | |
*headRef = newNode; | |
} | |
void printList(Node *head){ | |
while(head){ | |
printf("%d->", head->data); | |
head = head->next; | |
} | |
printf("Null"); | |
} | |
Node * findNthNode(Node *head, int n){ | |
if(!head) return NULL; | |
int counter = 0; | |
Node *first = head; | |
Node *second = head; | |
//If n is negative | |
if(n<0) { | |
printf("\n Wrong input: Negative n"); | |
} | |
while(first && counter < n){ | |
first = first->next; | |
counter++; | |
} | |
if(!first) { | |
printf("\n Not enough nodes in list to find nth node"); | |
return NULL; | |
} | |
while(first){ | |
first = first->next; | |
second = second->next; | |
} | |
return second; | |
} | |
int main(void) { | |
Node *head = NULL; | |
Node *nthNode = NULL; | |
push(&head, 3); | |
push(&head, 4); | |
Node * nodeToDelete = head; | |
push(&head, 5); | |
push(&head, 6); | |
push(&head, 7); | |
push(&head, 8); | |
push(&head, 9); | |
printf("\nOriginal list :"); | |
printList(head); | |
nthNode = findNthNode(head,3); | |
printf("\nNth node from end : %d", nthNode ? nthNode->data : 0); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment