Thread: Circular linked list

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Disturbed Boy gustavosserra's Avatar
    Join Date
    Apr 2003
    Posts
    244
    I think yes! Cur would be pointing to first. Then the next of the last (the first) will be pointing to next of the first, so, no one will be pointing to first. But usually the linked list is a pointer to the first element.
    Nothing more to tell about me...
    Happy day =)

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >I am trying to make sure I am understanding what I am reading.
    The best way to check your understanding is to write a small program that tests your assumptions:
    Code:
    /* Ugly quick code */
    #include <iostream>
    
    using namespace std;
    
    struct node {
      int   data;
      node *next;
      node(int init, node *link)
        : data(init)
        , next(link)
      {}
    };
    
    int
    main()
    {
      node *head, *tail;
    
      head = new node(0, 0);
      head->next = head;
      tail = head;
      for (int i = 1; i < 10; i++) {
        tail->next = new node(i, head);
        tail = tail->next;
      }
      for (tail = head; tail->next != head; tail = tail->next) {
        cout<< tail->data <<endl;
      }
      cout<< tail->data <<endl<<endl;
      node *cur = tail->next;
      tail->next = cur->next;
      for (tail = head; tail->next != head; tail = tail->next) {
        cout<< tail->data <<endl;
      }
      cout<< tail->data <<endl;
    }
    This clearly doesn't work when you run it. The problem is that tail->next will never point to head because head is the node that was removed from the list. You need to reseat head too:
    Code:
    node *cur = tail->next;
    tail->next = cur->next;
    head = tail->next;
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Duplicating value of pointer to linked list
    By zephyrcat in forum C Programming
    Replies: 14
    Last Post: 01-22-2008, 03:19 PM
  2. circular doubly linked list help
    By gunnerz in forum C++ Programming
    Replies: 5
    Last Post: 04-28-2007, 08:38 PM
  3. singly linked to doubly linked
    By jsbeckton in forum C Programming
    Replies: 10
    Last Post: 11-06-2005, 07:47 PM
  4. Problem with linked list ADT and incomplete structure
    By prawntoast in forum C Programming
    Replies: 1
    Last Post: 04-30-2005, 01:29 AM
  5. singly linked list
    By clarinetster in forum C Programming
    Replies: 2
    Last Post: 08-26-2001, 10:21 PM