Учитывая односвязный список, напишите функцию для парной замены элементов. Например, если связанный список 1-> 2-> 3-> 4-> 5-> 6-> 7 тогда функция должна изменить его на 2-> 1-> 4-> 3-> 6-> 5-> 7, и если связанный список будет 1-> 2-> 3-> 4-> 5-> 6, то функция должна изменить его на 2-> 1-> 4-> 3-> 6-> 5
Эта проблема обсуждалась здесь . Решение обеспечивает обмен данными между узлами. Если данные содержат много полей, будет много операций подкачки. Так что изменение ссылок — это лучшая идея в целом. Ниже приведена реализация C, которая изменяет ссылки, а не обменивается данными.
C ++
#include <bits/stdc++.h>
using namespace std;
class node {
public :
int data;
node* next;
};
node* pairWiseSwap(node* head) {
if (head == NULL || head->next == NULL)
return head;
node* remaing = head->next->next;
node* newhead = head->next;
head->next->next = head;
head->next = pairWiseSwap(remaing);
return newhead;
}
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;
}
}
int main()
{
node* start = NULL;
push(&start, 7);
push(&start, 6);
push(&start, 5);
push(&start, 4);
push(&start, 3);
push(&start, 2);
push(&start, 1);
cout << "Linked list before calling pairWiseSwap() " ;
printList(start);
start = pairWiseSwap(start);
cout << "\nLinked list after calling pairWiseSwap() " ;
printList(start);
return 0;
}
|
С
#include <stdbool.h> #include <stdio.h> #include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void pairWiseSwap( struct Node** head)
{
if (*head == NULL || (*head)->next == NULL)
return ;
struct Node* prev = *head;
struct Node* curr = (*head)->next;
*head = curr;
while ( true ) {
struct Node* next = curr->next;
curr->next = prev;
if (next == NULL || next->next == NULL) {
prev->next = next;
break ;
}
prev->next = next->next;
prev = next;
curr = prev->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;
}
}
int main()
{
struct Node* start = NULL;
push(&start, 7);
push(&start, 6);
push(&start, 5);
push(&start, 4);
push(&start, 3);
push(&start, 2);
push(&start, 1);
printf ( "\n Linked list before calling pairWiseSwap() " );
printList(start);
pairWiseSwap(&start);
printf ( "\n Linked list after calling pairWiseSwap() " );
printList(start);
getchar ();
return 0;
}
|
Джава
class LinkedList {
static Node head;
static class Node {
int data;
Node next;
Node( int d)
{
data = d;
next = null ;
}
}
Node pairWiseSwap(Node node)
{
if (node == null || node.next == null ) {
return node;
}
Node prev = node;
Node curr = node.next;
node = curr;
while ( true ) {
Node next = curr.next;
curr.next = prev;
if (next == null || next.next == null ) {
prev.next = next;
break ;
}
prev.next = next.next;
prev = next;
curr = prev.next;
}
return node;
}
void printList(Node node)
{
while (node != null ) {
System.out.print(node.data + " " );
node = node.next;
}
}
public static void main(String[] args)
{
LinkedList list = new LinkedList();
list.head = new Node( 1 );
list.head.next = new Node( 2 );
list.head.next.next = new Node( 3 );
list.head.next.next.next = new Node( 4 );
list.head.next.next.next.next = new Node( 5 );
list.head.next.next.next.next.next = new Node( 6 );
list.head.next.next.next.next.next.next = new Node( 7 );
System.out.println( "Linked list before calling pairwiseSwap() " );
list.printList(head);
Node st = list.pairWiseSwap(head);
System.out.println( "" );
System.out.println( "Linked list after calling pairwiseSwap() " );
list.printList(st);
System.out.println( "" );
}
}
|
C #
using System;
public class LinkedList {
Node head;
public class Node {
public int data;
public Node next;
public Node( int d)
{
data = d;
next = null ;
}
}
Node pairWiseSwap(Node node)
{
if (node == null || node.next == null ) {
return node;
}
Node prev = node;
Node curr = node.next;
node = curr;
while ( true ) {
Node next = curr.next;
curr.next = prev;
if (next == null || next.next == null ) {
prev.next = next;
break ;
}
prev.next = next.next;
prev = next;
curr = prev.next;
}
return node;
}
void printList(Node node)
{
while (node != null ) {
Console.Write(node.data + " " );
node = node.next;
}
}
public static void Main(String[] args)
{
LinkedList list = new LinkedList();
list.head = new Node(1);
list.head.next = new Node(2);
list.head.next.next = new Node(3);
list.head.next.next.next = new Node(4);
list.head.next.next.next.next = new Node(5);
list.head.next.next.next.next.next = new Node(6);
list.head.next.next.next.next.next.next = new Node(7);
Console.WriteLine( "Linked list before calling pairwiseSwap() " );
list.printList(list.head);
Node st = list.pairWiseSwap(list.head);
Console.WriteLine( "" );
Console.WriteLine( "Linked list after calling pairwiseSwap() " );
list.printList(st);
Console.WriteLine( "" );
}
}
|
Выход:
Linked list before calling pairWiseSwap() 1 2 3 4 5 6 7
Linked list after calling pairWiseSwap() 2 1 4 3 6 5 7
Сложность времени: временная сложность вышеупомянутой программы O (n), где n — количество узлов в данном связанном списке. Цикл while выполняет обход заданного связанного списка.
Ниже приводится рекурсивная реализация того же подхода. Мы меняем первые два узла и возвращаемся к оставшемуся списку. Спасибо Компьютерщику и Омеру Салему за предложение этого метода.
C ++
#include <bits/stdc++.h>
using namespace std;
class node {
public :
int data;
node* next;
};
node* pairWiseSwap(node* head) {
if (head == NULL || head->next == NULL)
return head;
node* remaing = head->next->next;
node* newhead = head->next;
head->next->next = head;
head->next = pairWiseSwap(remaing);
return newhead;
}
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;
}
}
int main()
{
node* start = NULL;
push(&start, 7);
push(&start, 6);
push(&start, 5);
push(&start, 4);
push(&start, 3);
push(&start, 2);
push(&start, 1);
cout << "Linked list before calling pairWiseSwap() " ;
printList(start);
start = pairWiseSwap(start);
cout << "\nLinked list after calling pairWiseSwap() " ;
printList(start);
return 0;
}
|
С
#include <stdbool.h> #include <stdio.h> #include <stdlib.h>
struct node {
int data;
struct node* next;
};
struct node* pairWiseSwap( struct node* head)
{
if (head == NULL || head->next == NULL)
return head;
struct node* remaing = head->next->next;
struct node* newhead = head->next;
head->next->next = head;
head->next = pairWiseSwap(remaing);
return newhead;
}
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;
}
}
int main()
{
struct node* start = NULL;
push(&start, 7);
push(&start, 6);
push(&start, 5);
push(&start, 4);
push(&start, 3);
push(&start, 2);
push(&start, 1);
printf ( "\n Linked list before calling pairWiseSwap() " );
printList(start);
start = pairWiseSwap(start);
printf ( "\n Linked list after calling pairWiseSwap() " );
printList(start);
return 0;
}
|
Джава
class LinkedList {
static Node head;
static class Node {
int data;
Node next;
Node( int d)
{
data = d;
next = null ;
}
}
Node pairWiseSwap(Node node)
{
if (node == null || node.next == null ) {
return node;
}
Node remaing = node.next.next;
Node newhead = node.next;
node.next.next = node;
node.next = pairWiseSwap(remaing);
return newhead;
}
void printList(Node node)
{
while (node != null ) {
System.out.print(node.data + " " );
node = node.next;
}
}
public static void main(String[] args)
{
LinkedList list = new LinkedList();
list.head = new Node( 1 );
list.head.next = new Node( 2 );
list.head.next.next = new Node( 3 );
list.head.next.next.next = new Node( 4 );
list.head.next.next.next.next = new Node( 5 );
list.head.next.next.next.next.next = new Node( 6 );
list.head.next.next.next.next.next.next = new Node( 7 );
System.out.println( "Linked list before calling pairwiseSwap() " );
list.printList(head);
head = list.pairWiseSwap(head);
System.out.println( "" );
System.out.println( "Linked list after calling pairwiseSwap() " );
list.printList(head);
System.out.println( "" );
}
}
|
C #
using System;
public class LinkedList {
Node head;
class Node {
public int data;
public Node next;
public Node( int d)
{
data = d;
next = null ;
}
}
Node pairWiseSwap(Node node)
{
if (node == null || node.next == null ) {
return node;
}
Node remaing = node.next.next;
Node newhead = node.next;
node.next.next = node;
node.next = pairWiseSwap(remaing);
return newhead;
}
void printList(Node node)
{
while (node != null ) {
Console.Write(node.data + " " );
node = node.next;
}
}
public static void Main()
{
LinkedList list = new LinkedList();
list.head = new Node(1);
list.head.next = new Node(2);
list.head.next.next = new Node(3);
list.head.next.next.next = new Node(4);
list.head.next.next.next.next = new Node(5);
list.head.next.next.next.next.next = new Node(6);
list.head.next.next.next.next.next.next = new Node(7);
Console.WriteLine( "Linked list before calling pairwiseSwap() " );
list.printList(list.head);
list.head = list.pairWiseSwap(list.head);
Console.WriteLine( "" );
Console.WriteLine( "Linked list after calling pairwiseSwap() " );
list.printList(list.head);
Console.WriteLine( "" );
}
}
|
Выход:
Linked list before calling pairWiseSwap() 1 2 3 4 5 6 7
Linked list after calling pairWiseSwap() 2 1 4 3 6 5 7
Попарно поменяйте местами соседние узлы связанного списка, изменив указатели | Набор 2
Эта статья предоставлена Гаутамом Кумаром . Пожалуйста, напишите комментарии, если вы обнаружите что-то неправильное, или вы хотите поделиться дополнительной информацией по обсуждаемой теме
Рекомендуемые посты:
Парная замена элементов данного связанного списка путем изменения ссылок
0.00 (0%) 0 votes