Data Structures | Linked List | Question 8

Last Updated :
Discuss
Comments

The following  function takes a single-linked list of integers as a parameter and rearranges the elements of the list. The function is called with the list containing the integers 1, 2, 3, 4, 5, 6, 7 in the given order. What will be the contents of the list after the function completes execution? 

C++
class Node {
public:
    int value;
    Node* next;
};

void rearrange(Node* list) {
    Node* p;
    Node* q;
    int temp;
    if (list == nullptr || list->next == nullptr) {
        return;
    }
    p = list;
    q = list->next;
    while (q != nullptr) {
        temp = p->value;
        p->value = q->value;
        q->value = temp;
        p = q->next;
        q = (p != nullptr) ? p->next : nullptr;
    }
}
C
struct Node {
    int value;
    struct Node* next;
};

void rearrange(struct Node* list) {
    struct Node* p;
    struct Node* q;
    int temp;
    if (list == NULL || list->next == NULL) {
        return;
    }
    p = list;
    q = list->next;
    while (q != NULL) {
        temp = p->value;
        p->value = q->value;
        q->value = temp;
        p = q->next;
        q = (p != NULL) ? p->next : NULL;
    }
}
Java
class Node {
    int value;
    Node next;
}

void rearrange(Node list) {
    Node p, q;
    int temp;
    if (list == null || list.next == null) {
        return;
    }
    p = list;
    q = list.next;
    while (q != null) {
        temp = p.value;
        p.value = q.value;
        q.value = temp;
        p = q.next;
        q = p != null ? p.next : null;
    }
}
Python
class Node:
    def __init__(self, value):
        self.value = value
        self.next = None


def rearrange(head):
    if head is None or head.next is None:
        return
    p = head
    q = head.next
    while q is not None:
        p.value, q.value = q.value, p.value
        p = q.next
        q = p.next if p is not None else None
JavaScript
class Node {
    constructor(value) {
        this.value = value;
        this.next = null;
    }
}

function rearrange(list) {
    if (list === null || list.next === null) {
        return;
    }
    let p = list;
    let q = list.next;
    while (q !== null) {
        [p.value, q.value] = [q.value, p.value];
        p = q.next;
        q = p !== null ? p.next : null;
    }
}

1,2,3,4,5,6,7

2,1,4,3,6,5,7

1,3,2,5,4,7,6

2,3,4,5,6,7,1

Share your thoughts in the comments