SCHOOL OF CODE BUILDERS
Learn To CODE. Become A DEVELOPER.
Pages
HOME
DATA STRUCTURES
STRINGS
ARRAYS
MATRIX
BINARY TREES
LINKED LIST
STACK
QUEUE
SORTING
SEARCHING
C
PYTHON
PSEUDOCODE
CONTEST PROBLEMS
ALGORITHMS
PATTERNS
PHP
C PUZZLES
C INTERVIEW QUESTIONS
JAVA
C++
HASHING
RECURSION
BASIC C PROGRAMS
TCS-CODEVITA
FACEBOOK
CONTACT US
Linked List Implementation(To get Nth node iterative)
Linked List Implementation(To get Nth node iterative)
Implementation:
#include
#include
/* structure of the node in the linked list */ struct node { int data; struct node *next; }; /* function to create a new node in the linked list */ struct node* newnode(int data) { struct node *new=(struct node*)malloc(sizeof(struct node)); new->data=data; new->next=NULL; return new; } /* function to insert the new node in the end of the linked list */ void insertastail(struct node **head,int data) { struct node *temp; struct node *current=*head; if(current==NULL) { *head=newnode(data); } else { temp=newnode(data); while(current->next!=NULL) current=current->next; current->next=temp; } } /* function to print the linked list */ void printlist(struct node *head) { struct node *current=head; while(current!=NULL) { printf("%d ",current->data); current=current->next; } } /* function to get the nth node of the linked list */ int getnthnode(struct node *head,int n) { int i=1; while(head!=NULL) { if(i==n) return head->data; head=head->next; i++; } return 0; } int main(void) { struct node *head=NULL; int data; int i,n; scanf("%d",&data); for(i=5;i<=data;i++) insertastail(&head,i); printlist(head); scanf("%d",&n); printf("\n%d",getnthnode(head,n)); return 0; }
PREVIOUS
NEXT
HOME