Reputation: 133
Working with linked lists, I am doing the following:
struct Node {
int val;
struct Node* prev;
struct Node* next;
};
struct Node* head;
struct Node* tail;
struct Node* temp;
where Node is a structure for linked list, head points to first element, tail to the last, temp is for intermediate computation.
move_function(address1, address2)
actually swaps node at addresses 1&2 by suitably changing their prev, next pointers.
void move(struct Node* t1, struct Node* t2) //known that t1->next ..... ->next = t2, move from t2 to t1
{
cout << "move";
if (t1->next == t2)
{
cout << " Conseq";
temp1 = t1->prev;
temp2 = t2->next;
t1->next = temp2; if (temp2 != NULL) temp2->prev = t1;
t2->prev = temp1; if (temp1 != NULL) temp1->next = t2;
t2->next = t1;
t1->prev = t2;
}
else
{
cout << "...";
t2->prev->next = t2->next;
if (t2->next != NULL) { t2->next->prev = t2->prev; }
if (t1 != head) { t1->prev->next = t2; t2->prev = t1->prev; t2->next = t1; t1->prev = t2; }
else { head = t2; t2->prev = NULL; t2->next = t1; t1->prev = t2; }
}
}
if (<node to be shifted is the last one i.e. *tail*>)
{
temp = tail->prev;
move_function (head, tail);
tail= temp;
}
It turns out that while writing temp = tail->prev;
temp retains the definition, and not what I want i.e. the address of the element behind it (which needs to be set as tail after movement). More concretely, in the end, after executing move_function (head, tail); tail=temp;
contrary to what I want, for number of elements in list = =2,tail->prev == NULL is true.
What I really want is to remember my last element after movement.
What is happening here, and how do I work around? While writing, temp = tail->prev
, if node at tail is shifted to head position and its prev set to NULL, does temp->prev
become NULL
?
Thanks!
Upvotes: 0
Views: 147
Reputation: 11506
This is why it's a bad idea to declare multiple variables on a single line. The problem is that only head
is a pointer. I.e. the following two pieces of code are equivalent:
// The way you declared the variables:
struct Node* head, tail, temp;
// Above is equivalent to:
struct Node* head;
struct Node tail;
struct Node temp;
Simply define each variable on a separate line. It will make the code more readable and fix it at the same time.
Live demo of the issue with your declarations: https://godbolt.org/z/f154dT.
Edit: Also, since you're writing C++, not C, there's no reason to put struct
there. Just use Node * head;
.
Upvotes: 1