Hi,
I've coded a program to find the nth node from the end of the linked list.
It works and get me the right result, but I am puzzled as why I get the
compiler warnings at the following line,
p1 = p1->next;
findnthnode.c:28: warning: assignment from incompatible pointer type
Thanks in advance,
//////////////// Code listing below /////////////////////////
//Q: In a linked list find the nth node from the end of this list.
#include <stdio.h>
// algorithm : use two pointers and they're n-1 nodes apart. when first
reach the end, 2nd one reaches nth node.
typedef struct {
struct node* next;
int data;
}node;
node* findnthnode(node *head, int n)
{
node *p1;
node *p2;
p1 = head;
p2 = NULL;
// if head is null, return null
// if n > length of list, return null
// if n = 0, we return the tail.
// if there're two nodes,
// n=0, we return node2,
// n=1, we return node1(head)
// n>=2, we return NULL
// let p1 go n-1 steps
for (; n>0 && p1 ; n--){
p1 = p1->next;
}
if (!p1)
return NULL;
else
p2 = head;
// move p1, p2 together to traverse list
while (p1 && p1->next){
p1 = p1->next;
p2 = p2->next;
}
return p2;
}
int main()
{
// build a list
node a[3] = {0};
node *p;
int i;
a[0].data = 2;
a[0].next = &a[1];
a[1].data = 5;
a[1].next = &a[2];
a[2].data = 3;
a[2].next = NULL;
for (i=0;i<4;i++){
p = findnthnode(a, i);
if (p)
printf("found %dth node = %d\n",i, p->data);
else
printf("not found!\n");
}
return 0;
}