Write code that divides the linked list into two parts with the given value x as a datum, and all nodes that are less than X are ranked before nodes greater than or equal to X.
/* The first node of the incoming list, and the value as the base of the linked list */
#include <iostream>
using namespace Std;
typedef struct NODE
{
int data;
struct node* next;
}* LinkedListNode;
LinkedListNode partition (LinkedListNode node, int x)
{
LinkedListNode Beforestart = NULL;
LinkedListNode beforend = NULL;
LinkedListNode Afterstart = NULL;
LinkedListNode afterend = NULL;
/* Split linked list */
while (node! = NULL)
{
LinkedListNode next = node->next;
Node->next = NULL;
if (Node->data < x)
{
/* Insert nodes into the before list */
if (Beforestart = = NULL)
{
Beforestart = node;
Beforend = Beforestart;
}
Else
{
Beforend->next = node;
beforend = node;
}
}
Else
{
/* Insert the node into the after list */
if (Afterstart = NULL)
{
Afterstart = node;
Afterend = Afterstart;
}
Else
{
Afterend->next = node;
afterend = node;
}
}
node = next;
}//end while
if (Beforestart = = NULL)
return afterstart;
Merging before and after linked lists
Beforend->next = Afterstart;
return beforestart;
}
/* The first node of the incoming list, and the value as the base of the linked list */
#include <iostream>
using namespace Std;
typedef struct NODE
{
int data;
struct node* next;
}*linkedlistnode;
LinkedListNode partition (LinkedListNode node, int x)
{
LinkedListNode Beforestart = NULL;
LinkedListNode Afterstart = NULL;
/* Split linked list */
while (node! = NULL)
{
LinkedListNode next = node->next;
Node->next = NULL;
if (Node->data < x)
{
/* INSERT nodes into the front of the Before list */
node->next=beforestart;
Beforestart = node;
}
Else
{
/* Insert the node into the after list */
node->next=afterstart;
Afterstart=node;
}
node = next;
}//end while
if (Beforestart = = NULL)
return afterstart;
Merging before and after linked lists
while (beforestart->next! = NULL)
{
Beforestart = beforestart->next;
}
Beforestart->next = Afterstart;
return beforestart;
}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Value x divides the list into two parts, and nodes less than x are ranked before nodes greater than or equal to X