简体   繁体   中英

doubly linked list swap explanation

'Write a procedure to swap the first two nodes of a doubly linked list.'

Can someone explain this thing using images?

 void swapFirstTwo() { if (head != tail) { DLLNode neck = head.next; head.next = neck.next; neck.next = head; head.prev = neck; neck.prev = null; if (tail == neck) // two element list tail = head; head = neck; } }

Example-1

1<=>2<=>3->null

structure-

1.next = 2;2.next = 3;3.next = null; 1.prev = null;2.prev = 1;3.prev = 2;

To swap the first two elements means to swap their positions. So once the swapping is done, the list will look like this- 2<=>1<=>3->null

This is how the code you have pasted gives the expected result-

neck = head.next; neck = 2;

neck.next = head; 2.next = 1;

head.prev = neck; 1.prev = 2;

head.next = neck.next; 1.next = 3;

neck.prev = null; 2.prev = null;

Basically, the next and prev pointers of 1 & 2 are exchanged. On adding up all the steps above, you get-

2.next = 1;1.next = 3;3.next = null 2.prev=null;1.prev = 2;3.prev = 2;

But one step missing in the above logic is the head should be pointing to neck. Since, head changes on swapping the elements.

Example-2

In case there's only one element in the list, swapping won't be necessary

Example-3

In case, there are only two elements, along with changing the pointer of head, since tail(end) of the list is maintained, you will have update the tail as well as tail would be pointing to the current head after exchange instead it should point to the current neck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM