if( strcmp(z->Rev->x.y,z->x.y) > 0)

In this statement i want to swap the pNext and pPrev. How will be the assignment look like?

Dani AI

Generated

The posts show a string comparison deciding whether two list nodes should change order. Two practical approaches exist: swap the node payload (simpler and less error-prone) or relink nodes (required when external pointers must keep pointing to the same node objects). Swapping links must treat adjacent and non‑adjacent cases separately and must update the head (and tail) where needed. ’s comparisons can drive either approach; ’s pointer to sorting threads is useful if the goal is full-list sorting rather than one-off swaps.

Example sequences for adjacent swaps (C). For a singly linked list, caller provides the node before the pair (or NULL if the pair starts at head):

typedef struct Node {
    char *data;
    struct Node *next;
} Node;

void swap_adjacent_singly(Node **head, Node *prev, Node *a, Node *b) {
    if (!head || !a || !b || a->next != b) return;
    if (prev) prev->next = b; else *head = b;
    a->next = b->next;
    b->next = a;
}

For a doubly linked list the sequence needs to fix four neighbor pointers and the head if applicable:

typedef struct DNode {
    char *data;
    struct DNode *prev;
    struct DNode *next;
} DNode;

void swap_adjacent_doubly(DNode **head, DNode *a, DNode *b) {
    if (!head || !a || !b || a->next != b) return;
    DNode *prev = a->prev;
    DNode *next = b->next;
    if (prev) prev->next = b; else *head = b;
    b->prev = prev;
    b->next = a;
    a->prev = b;
    a->next = next;
    if (next) next->prev = a;
}

Troubleshooting notes: always check for NULLs and that nodes are adjacent when using these helpers; handle the non‑adjacent swap by saving a_prev/a_next/b_prev/b_next and updating four pointers (or reuse list splice helpers). For simple sorting of values, swapping payload fields is often faster and much simpler to get right. Test on tiny lists (head/tail/middle) and add assertions or prints to catch pointer mistakes early.

Recommended Answers

All 2 Replies

C Programming: How to change position of nodes in a link list?
How to change position of nodes in a link list?

if( strcmp(current->Next->a.data,current->a.data) < 0){

I want current->next to be the current and current to be the current -> next?
How to do it?What is the assignment?
How to swap positions or links like this

Not swapped
(C B A )

Swapped

(A B C)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.