Answer to Question #226416 in C for Morgan

Question #226416

A class octopus has a dummy head which has four pointers – left, right, top and bottom. You have to build link list in these 4 directions depending on the input commands. There will be four types of commands – L, R, T and B. Their specifications are given below:

L x: insert x in the left link list // Where x is an integer number.

R x: insert x in the right link list

T x: insert x in the top link list

B x: insert x in the bottom link list

Input: Test case will start with a number n indicating the number of lines following it.

Output: you have to give output that which link list (Left, Right, Top and Bottom) has maximum sum of values. See the sample input and output.

Sample input

14

L 3

L 15

L 1

R 17

T 9

T 10

B 13

T 5

L 8

R 3

R 12

B 2

B 3

B 4

Sample output

Right Link List Has Maximum Sum 32


1
Expert's answer
2021-08-17T12:56:01-0400
public ListNode swapPairs(ListNode head) {
    
    if (head != null && head.next != null) {
        ListNode n1 = head;
        ListNode n2 = n1.next;

        head = n2;
        n1.next = n2.next;
        n2.next = n1;                   
        ListNode pred = n1;
        while (pred.next != null && pred.next.next != null) {
            n1 = pred.next;
            n2 = n1.next;

            pred.next = n2;
            n1.next = n2.next;
            n2.next = n1;                   
            pred = n1;
        }
    }
    return head;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS