⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 nthnode.txt

📁 It is an ebook about data structures,mainly linked list
💻 TXT
字号:
  
   
Write a C program to return the nth node from the end of a linked list. 

Discuss it!          



Suppose one needs to get to the 6th node from the end in this LL. First, just keep on incrementing the first pointer (ptr1) till the number of increments cross n (which is 6 in this case) 


STEP 1    :   1(ptr1,ptr2) -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10 

STEP 2    :   1(ptr2) -> 2 -> 3 -> 4 -> 5 -> 6(ptr1) -> 7 -> 8 -> 9 -> 10 



Now, start the second pointer (ptr2) and keep on incrementing it till the first pointer (ptr1) reaches the end of the LL. 


STEP 3    :   1 -> 2 -> 3 -> 4(ptr2) -> 5 -> 6 -> 7 -> 8 -> 9 -> 10 (ptr1) 


So here you have!, the 6th node from the end pointed to by ptr2! 


Here is some C code.. 


struct node 
{ 
  int data; 
  struct node *next; 
}mynode; 


mynode * nthNode(mynode *head, int n /*pass 0 for last node*/) 
{ 
  mynode *ptr1,*ptr2; 
  int count; 

  if(!head) 
  { 
    return(NULL); 
  } 

  ptr1  = head; 
  ptr2  = head; 
  count = 0; 

  while(count < n) 
  { 
     count++; 
     if((ptr1=ptr1->next)==NULL) 
     { 
        //Length of the linked list less than n. Error. 
        return(NULL); 
     } 
  } 

  while((ptr1=ptr1->next)!=NULL) 
  { 
    ptr2=ptr2->next; 
  } 

  return(ptr2); 
} 


 
 
 

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -