I am not sure (let's wait the answer from the experts...) but I think
that you have not created a struct node, you created a different thing
(typedef).

So the variable "next", inside the structure is from a different type of p1.

Do a little test: remove the typedef, create a real struct node:

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

And create p1 and p2 with

struct node *p1;
struct node *p2;

Best regards,

carlos



On Mon, Oct 27, 2008 at 12:54 AM, frank zhu <[EMAIL PROTECTED]> wrote:
> 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;
> }
>
> 



-- 
=============================================
Carlos José de Almeida Pereira
Ilhéus - Bahia - Brasil

BLOG:
      http://starfightercarlao.blogspot.com
      http://starfightercarlaoenglish.blogspot.com (english version)


"Felicidade se acha é em horinhas de descuido."

"Qualquer amor já é um pouquinho de saúde, um descanso na loucura."

                                                  (Guimarães Rosa, ambas)

Reply via email to