Учитывая связанный список, задача состоит в том, чтобы проверить, отсортирован ли связанный список в порядке убывания или нет?
Примеры :
Ввод: 8 -> 7 -> 5 -> 2 -> 1.
Выход: Да
Объяснение :
В данном связном списке, начиная с головы,
8> 7> 5> 2> 1. Итак, сортировка выполняется в обратном порядке.
Ввод: 24 -> 12 -> 9 -> 11 -> 8 -> 2.
Выход: Нет
Рекомендуется: сначала попробуйте свой подход в {IDE}, прежде чем переходить к решению.
Итерационный подход: просмотрите связанный список от начала до конца. Для каждого вновь обнаруженного элемента проверьте узел -> данные> узел -> следующий -> данные . Если True, сделайте то же самое для каждого узла, иначе верните 0 и выведите «Нет».
C ++
#include <bits/stdc++.h> using namespace std; struct Node { data; int
struct Node* next;
}; bool isSortedDesc( struct Node *head) { if (head == NULL)
return true ;
for (Node *t=head; t->next != NULL; t=t->next)
if (t->data <= t->next->data)
return false ;
return true ;
} Node *newNode( data) int { Node *temp = new Node;
temp->next = NULL;
temp->data = data;
} int main() { struct Node *head = newNode(7);
head->next = newNode(5);
head->next->next = newNode(4);
head->next->next->next = newNode(3);
isSortedDesc(head) ? cout << "Yes" :
cout << "No" ;
return 0;
} |
Джава
class GFG { static class Node { data; int
Node next;
}; static boolean isSortedDesc(Node head) { if (head == null )
return true ;
for (Node t = head; t.next != null ; t = t.next)
if (t.data <= t.next.data)
return false ;
return true ;
} static Node newNode( data) int { Node temp = new Node();
temp.next = null ;
temp.data = data;
return temp;
} public static void main(String[] args) { Node head = newNode( 7 );
head.next = newNode( 5 );
head.next.next = newNode( 4 );
head.next.next.next = newNode( 3 );
if (isSortedDesc(head))
System.out.println( "Yes" );
else
System.out.println( "No" );
} } |
Python3
class Node: def __init__( self , data):
self .data = data;
self . next = next ;
def isSortedDesc(head): if (head = = None ):
return True ;
while (head. next ! = None ):
t = head;
if (t.data < = t. next .data):
return False ;
head = head. next
return True ;
def newNode(data): temp = Node( 0 );
temp. next = None ;
temp.data = data;
return temp;
if __name__ = = '__main__' : head = newNode( 7 );
head. next = newNode( 5 );
head. next . next = newNode( 4 );
head. next . next . next = newNode( 3 );
if (isSortedDesc(head)):
print ( "Yes" );
else :
print ( "No" );
|
C #
using System;
class GFG
{ public class Node { public data; int
public Node next;
}; static bool isSortedDesc(Node head) { if (head == null )
return true ;
for (Node t = head;
t.next != null ; t = t.next)
if (t.data <= t.next.data)
return false ;
return true ;
} static Node newNode( data) int { Node temp = new Node();
temp.next = null ;
temp.data = data;
return temp;
} public static void Main(String[] args) { Node head = newNode(7);
head.next = newNode(5);
head.next.next = newNode(4);
head.next.next.next = newNode(3);
if (isSortedDesc(head))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
} } |
Сложность времени: O (N), где N - длина связанного списка.
Рекурсивный подход:
Рекурсивно проверьте этот узел -> данные> узел -> следующий -> данные. Если нет, верните 0, что является нашим завершенным условием выхода из рекурсии. Else Вызовите функцию Check_List рекурсивно для следующего узла.
C ++
#include <bits/stdc++.h> using namespace std; struct Node { data; int
struct Node* next;
}; bool isSortedDesc( struct Node *head) {
if (head == NULL || head->next == NULL)
return true ;
return (head->data > head->next->data &&
isSortedDesc(head->next));
} Node *newNode( data) int { Node *temp = new Node;
temp->next = NULL;
temp->data = data;
} int main() { struct Node *head = newNode(7);
head->next = newNode(5);
head->next->next = newNode(4);
head->next->next->next = newNode(3);
isSortedDesc(head) ? cout << "Yes" :
cout << "No" ;
return 0;
} |
Джава
class GfG { static class Node { data; int
Node next;
} static boolean isSortedDesc(Node head) {
if (head == null || head.next == null )
return true ;
return (head.data > head.next.data && isSortedDesc(head.next));
} static Node newNode( data) int { Node temp = new Node(); temp.next = null ; temp.data = data; return temp; } public static void main(String[] args) { Node head = newNode( 7 );
head.next = newNode( 5 );
head.next.next = newNode( 4 );
head.next.next.next = newNode( 3 );
if (isSortedDesc(head) == true )
System.out.println( "Yes" );
else
System.out.println( "No" );
}
} |
Python3
class Node:
def __init__( self , data):
self .data = data
self . next = None
def isSortedDesc(head):
if (head = = None or head. next = = None ):
return True
return (head.data > head. next .data and
isSortedDesc(head. next ))
def newNode(data): temp = Node(data)
return temp
if __name__ = = "__main__" :
head = newNode( 7 )
head. next = newNode( 5 )
head. next . next = newNode( 4 )
head. next . next . next = newNode( 3 )
if isSortedDesc(head):
print ( "Yes" )
else :
print ( "No" )
|
C #
using System; class GfG { public class Node { public data; int
public Node next;
} static bool isSortedDesc(Node head) {
if (head == null || head.next == null )
return true ;
return (head.data > head.next.data &&
isSortedDesc(head.next));
} static Node newNode( data) int { Node temp = new Node();
temp.next = null ;
temp.data = data;
return temp;
} public static void Main(String[] args) { Node head = newNode(7);
head.next = newNode(5);
head.next.next = newNode(4);
head.next.next.next = newNode(3);
if (isSortedDesc(head) == true )
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
} |
Вниманию читателя! Не прекращайте учиться сейчас. Освойте все важные концепции DSA с помощью самостоятельного курса DSA по доступной для студентов цене и будьте готовы к работе в отрасли. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .
Если вы хотите посещать живые занятия с отраслевыми экспертами, пожалуйста, обращайтесь к Geeks Classes Live и Geeks Classes Live USA.