In: Computer Science
C++ language or Python.
Linked Lists
You are given a linked list that contains N integers. You are to perform the following reverse operation on the list:
Select all the subparts of the list that contain only even integers. For example, if the list is {1,2,8,9,12,16}, then the selected subparts will be {2,8}, {12,16}.
Reverse the selected subpart such as {8,2} and {16,12}.
The list should now be {1,8,2,9,16,12}.
Your node definition should consist of 2 elements: the integer value and a pointer to a node.
Sample Input
9 2 18 24 3 5 7 9 6 12
Sample Output:
24 18 2 3 5 7 9 12 6
C++
// Iterative C++ program to reverse
// a linked list
#include <iostream>
using
namespace
std;
/* Link list node */
struct
Node {
int
data;
struct
Node* next;
Node(
int
data)
{
this
->data
= data;
next
= NULL;
}
};
struct
LinkedList {
Node*
head;
LinkedList()
{
head
= NULL;
}
/* Function to
reverse the linked list */
void
reverse()
{
//
Initialize current, previous and
//
next pointers
Node*
current = head;
Node
*prev = NULL, *next = NULL;
while
(current != NULL) {
//
Store next
next
= current->next;
//
Reverse current node's pointer
current->next
= prev;
//
Move pointers one position ahead.
prev
= current;
current
= next;
}
head
= prev;
}
/* Function to print
linked list */
void
print()
{
struct
Node* temp = head;
while
(temp != NULL) {
cout
<< temp->data <<
"
"
;
temp
= temp->next;
}
}
void
push(
int
data)
{
Node*
temp =
new
Node(data);
temp->next
= head;
head
= temp;
}
};
/* Driver program to test above function*/
int
main()
{
/* Start with the
empty list */
LinkedList
ll;
ll.push(20);
ll.push(4);
ll.push(15);
ll.push(85);
cout <<
"Given linked list\n"
;
ll.print();
ll.reverse();
cout <<
"\nReversed Linked list \n"
;
ll.print();
return
0;
}
Python
|