简体   繁体   中英

Swap group of nodes in a doubly linked list

I came across this problem in which you should swap a group of nodes in a doubly linked list. For example: for the list 1 <-> 2 <-> 3 <-> 4 <-> 5 <-> 6 <-> 7 <-> 8 and the given intervals 2-4 and 6-7 you should swap the nodes in the interval as a group with the other nodes in the interval, getting the output 1 <-> 6 <-> 7 <-> 5 <-> 2 <-> 3 <-> 4 <-> 8 . I have the idea to treat the whole group as a single node, meaning I should connect 6.prev with 1 and 7.next with 5, but because this is a doubly linked list, I find it hard to think of a solution that would change all the needed pointers successfully. Can someone help me and explain to me how should this be done? Thanks.

The "node" in double linked list has 2 pointer: -next element -previous element

You should copy the pointer of the first and last element of both interval

-First1,Last1 = 2,4 //(i mean the pointer to 2 and 4 not integer)
-First2,Last2 = 6,7

As final operation to swap interval you should say

(First2.previous).next = First1  // ( First2.previous is 5 in the example)
(Next2.next).previous = Next1   // (Next2.next is 8 in the example)

(First1.previous).next = First2 //(First1.previous is 1)
(Next1.next).previous = Next2   //(Next1.next is 5)

Doubly Linked List have head and tail . Also each node have prev and next pointers which are null if node is head or tail respectively.

Our assumption here is that 2 segments to be swapped (start1-end1) and (start2-end2) are not overlapping.

Copy all prev and next references to temp variables

1. prev1=start1.prev, prev2=start2.prev, next1=end1.next, next2=end2.next

Swap start1 and start2 , and handle condition if start1 was head

2. start2.prev=prev1
3. if prev1=null, head=start2 else prev1.next=start2
4. start1.prev=prev2
5. prev2.next=start1

Swap end1 and end2 , and handle condition if end2 was tail

6. end1.next=next2
7. if next2=null, tail=end1 else next2.prev=end1
8. end2.next=next1
9. next1.prev=end2

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