CS2303 Tutorial Week 2 Exercises:
Suppose we have a pointer to a node in a singly linked list that is guaranteed not to be the last node in the list. We do not have pointers to any other nodes (except by following links). Describe an algorithm that logically removes the value stored in such a node from the linked list, maintaining the integrity of the linked list.
Solution: Suppose the pointer to the node is p.
p->data=p->next->data;
p->next=p->next->next;
In singly linked list, write a member function Swap(ListNode* p ListNode* q) which swaps the order of the adjacent two nodes pointed by p and q (p->next==q). You can only change the links (not data)in your implementation.
Solution:
List::Swap(ListNode* p ListNode* q)
{
if (p==first)
{
p->next=q->next;
q->next=p;
first=q;
}
else
{
s=first;
while (s->next!=p)
s=s->next;
p->next=q->next;
s->next=q;
q->next=p;
}
}