Учитывая связанный список 0, 1 и 2, сортируйте его.
Примеры :
Input: 1 -> 1 -> 2 -> 0 -> 2 -> 0 -> 1 -> NULL
Output: 0 -> 0 -> 1 -> 1 -> 1 -> 2 -> 2 -> NULL
Input: 1 -> 1 -> 2 -> 1 -> 0 -> NULL
Output: 0 -> 1 -> 1 -> 1 -> 2 -> NULL
Источник: Microsoft Интервью | Комплект 1
Следующие шаги могут быть использованы для сортировки данного связанного списка.
- Пройдите по списку и посчитайте количество 0, 1 и 2. Пусть счетами будут n1, n2 и n3 соответственно.
- Снова пройдите по списку, заполните первые n1 узлы 0, затем n2 узлы 1 и, наконец, n3 узлы 2.
Ниже приведен пробный запуск вышеуказанного подхода:

Ниже приведена реализация вышеуказанного подхода:
C ++
#include <bits/stdc++.h>
using namespace std;
class Node
{
public :
int data;
Node* next;
};
void sortList(Node *head)
{
int count[3] = {0, 0, 0};
Node *ptr = head;
while (ptr != NULL)
{
count[ptr->data] += 1;
ptr = ptr->next;
}
int i = 0;
ptr = head;
while (ptr != NULL)
{
if (count[i] == 0)
++i;
else
{
ptr->data = i;
--count[i];
ptr = ptr->next;
}
}
}
void push (Node** head_ref, int new_data)
{
Node* new_node = new Node();
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void printList(Node *node)
{
while (node != NULL)
{
cout << node->data << " " ;
node = node->next;
}
cout << endl;
}
int main( void )
{
Node *head = NULL;
push(&head, 0);
push(&head, 1);
push(&head, 0);
push(&head, 2);
push(&head, 1);
push(&head, 1);
push(&head, 2);
push(&head, 1);
push(&head, 2);
cout << "Linked List Before Sorting\n" ;
printList(head);
sortList(head);
cout << "Linked List After Sorting\n" ;
printList(head);
return 0;
}
|
С
#include<stdio.h> #include<stdlib.h>
struct Node
{
int data;
struct Node* next;
};
void sortList( struct Node *head)
{
int count[3] = {0, 0, 0};
struct Node *ptr = head;
while (ptr != NULL)
{
count[ptr->data] += 1;
ptr = ptr->next;
}
int i = 0;
ptr = head;
while (ptr != NULL)
{
if (count[i] == 0)
++i;
else
{
ptr->data = i;
--count[i];
ptr = ptr->next;
}
}
}
void push ( struct Node** head_ref, int new_data)
{
struct Node* new_node =
( struct Node*) malloc ( sizeof ( struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void printList( struct Node *node)
{
while (node != NULL)
{
printf ( "%d " , node->data);
node = node->next;
}
printf ( "n" );
}
int main( void )
{
struct Node *head = NULL;
push(&head, 0);
push(&head, 1);
push(&head, 0);
push(&head, 2);
push(&head, 1);
push(&head, 1);
push(&head, 2);
push(&head, 1);
push(&head, 2);
printf ( "Linked List Before Sorting\n" );
printList(head);
sortList(head);
printf ( "Linked List After Sorting\n" );
printList(head);
return 0;
}
|
Джава
class LinkedList
{
Node head;
class Node
{
int data;
Node next;
Node( int d) {data = d; next = null ; }
}
void sortList()
{
int count[] = { 0 , 0 , 0 };
Node ptr = head;
while (ptr != null )
{
count[ptr.data]++;
ptr = ptr.next;
}
int i = 0 ;
ptr = head;
while (ptr != null )
{
if (count[i] == 0 )
i++;
else
{
ptr.data= i;
--count[i];
ptr = ptr.next;
}
}
}
public void push( int new_data)
{
Node new_node = new Node(new_data);
new_node.next = head;
head = new_node;
}
void printList()
{
Node temp = head;
while (temp != null )
{
System.out.print(temp.data+ " " );
temp = temp.next;
}
System.out.println();
}
public static void main(String args[])
{
LinkedList llist = new LinkedList();
llist.push( 0 );
llist.push( 1 );
llist.push( 0 );
llist.push( 2 );
llist.push( 1 );
llist.push( 1 );
llist.push( 2 );
llist.push( 1 );
llist.push( 2 );
System.out.println( "Linked List before sorting" );
llist.printList();
llist.sortList();
System.out.println( "Linked List after sorting" );
llist.printList();
}
}
|
питон
class LinkedList( object ):
def __init__( self ):
self .head = None
class Node( object ):
def __init__( self , d):
self .data = d
self . next = None
def sortList( self ):
count = [ 0 , 0 , 0 ]
ptr = self .head
while ptr ! = None :
count[ptr.data] + = 1
ptr = ptr. next
i = 0
ptr = self .head
while ptr ! = None :
if count[i] = = 0 :
i + = 1
else :
ptr.data = i
count[i] - = 1
ptr = ptr. next
def push( self , new_data):
new_node = self .Node(new_data)
new_node. next = self .head
self .head = new_node
def printList( self ):
temp = self .head
while temp ! = None :
print str (temp.data),
temp = temp. next
print ''
llist = LinkedList()
llist.push( 0 )
llist.push( 1 )
llist.push( 0 )
llist.push( 2 )
llist.push( 1 )
llist.push( 1 )
llist.push( 2 )
llist.push( 1 )
llist.push( 2 )
print "Linked List before sorting"
llist.printList()
llist.sortList()
print "Linked List after sorting"
llist.printList()
|
C #
using System;
public class LinkedList
{
Node head;
class Node
{
public int data;
public Node next;
public Node( int d)
{
data = d; next = null ;
}
}
void sortList()
{
int []count = {0, 0, 0};
Node ptr = head;
while (ptr != null )
{
count[ptr.data]++;
ptr = ptr.next;
}
int i = 0;
ptr = head;
while (ptr != null )
{
if (count[i] == 0)
i++;
else
{
ptr.data= i;
--count[i];
ptr = ptr.next;
}
}
}
public void push( int new_data)
{
Node new_node = new Node(new_data);
new_node.next = head;
head = new_node;
}
void printList()
{
Node temp = head;
while (temp != null )
{
Console.Write(temp.data+ " " );
temp = temp.next;
}
Console.WriteLine();
}
public static void Main(String []args)
{
LinkedList llist = new LinkedList();
llist.push(0);
llist.push(1);
llist.push(0);
llist.push(2);
llist.push(1);
llist.push(1);
llist.push(2);
llist.push(1);
llist.push(2);
Console.WriteLine( "Linked List before sorting" );
llist.printList();
llist.sortList();
Console.WriteLine( "Linked List after sorting" );
llist.printList();
}
}
|
Выход:
Linked List Before Sorting
2 1 2 1 1 2 0 1 0
Linked List After Sorting
0 0 1 1 1 1 2 2 2
Сложность времени: O (n), где n — количество узлов в связанном списке.
Вспомогательное пространство: O (1)
Сортировать связанный список 0, 1 и 2 путем изменения ссылок
Эта статья составлена Нарендрой Кангралкар . Пожалуйста, пишите комментарии, если вы обнаружите что-то неправильное или вы хотите поделиться дополнительной информацией по обсуждаемой выше теме.
Рекомендуемые посты:
Сортировать связанный список 0, 1 и 2
0.00 (0%) 0 votes