Vous êtes sur la page 1sur 1

I Problem DS-03-03 Swap two adjacent elements by adjusting only the pointers (and

not the data) using: (a) singly linked lists (b) doubly linked lists.
Solution. (a) Suppose that BeforeP points to the node before the two adjacent nodes
that are to be swapped.

void SwapTwoAdjacentNodes_Single(Position BeforeP, List L)


{
Position P, AfterP;

P = BeforeP->Next;
AfterP = P->Next;

P->Next = AfterP->Next;
BeforeP->Next = AfterP;
AfterP->Next = P;
}

(b) Suppose that the declaration of node for doubly linked list is as follows:

struct Node
{
ElementType Element;
Position Prev;
Position Next;
}

The following procedure can be used to swap node pointed by P and the node after P .

void SwapTwoAdjacentNodes_Double(Position P, List L)


{
Position BeforeP, AftertP;

BeforeP = P->Prev;
AfterP = P->Next;

P->Next = AftertP->Next;
BeforeP->Next = AfterP;
AfterP->Next = P;
P->Next->Prev = P;
P->Prev = AfterP;
AfterP->Prev = BeforeP;
}

Vous aimerez peut-être aussi