If I have an external pointer List pointing to the "last" node, would this statemnet disconnect the node at the "beginning" of the list??
Thanks!!
Code:Cur = List -> Next;
List -> Next = Cur -> Next;
Printable View
If I have an external pointer List pointing to the "last" node, would this statemnet disconnect the node at the "beginning" of the list??
Thanks!!
Code:Cur = List -> Next;
List -> Next = Cur -> Next;
Have you tried it? Did it work? :)
No, I did not write a program, I am just reading and learning about linked lists and I am trying to make sure I am understanding what I am reading.
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.
>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:
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:/* 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;
}
Code:node *cur = tail->next;
tail->next = cur->next;
head = tail->next;
Hi Prelude! Just a question about your code. I know that is that only way to initialize const member, but way use that kind of initialization in node constructor instead of inside the definition?
Sorry for changing the topic a little bit.
>but way use that kind of initialization in node constructor instead of inside the definition?
Because it never hurts and sometimes helps (in the case of const or reference members or avoiding default construction and then assignment for objects). I try to use an initialization list for my constructors as much as possible to remain consistent and avoid hairy situations. ;)
Ok! Thanks!