#include<iostream>
using
namespace
std;
class
Node
{
public
:
int
data;
Node* next;
Node(
int
d) {
data = d;
next = NULL;
}
};
void
insertAtTail(Node*& head, Node*& tail,
int
d ) {
Node* newnode =
new
Node(d);
if
(tail == NULL) {
tail = head = newnode;
return
;
}
tail->next = newnode;
tail = newnode;
}
void
insertAtHead(Node*& head, Node*& tail,
Node*& deletedNode)
{
if
(head == NULL) {
head = tail = deletedNode;
return
;
}
deletedNode->next = head;
head = deletedNode;
return
;
}
Node* deleteAtTail(Node*& head, Node*& tail) {
Node* deleted = tail;
Node* temp = head;
while
(temp->next->next != NULL) {
temp = temp->next;
}
temp->next = NULL;
tail = temp;
return
deleted;
}
void
appendAtFront(Node*& head, Node*& tail,
int
n,
int
k)
{
k = k % n;
while
(k != 0) {
Node* deleted = deleteAtTail(head, tail);
insertAtHead(head, tail, deleted);
k--;
}
}
void
printLinkedList(Node* head) {
while
(head != NULL) {
cout << head->data <<
" "
;
head = head->next;
}
cout << endl;
}
int
main()
{
Node* head = NULL;
Node* tail = NULL;
int
n = 6;
insertAtTail(head, tail, 1);
insertAtTail(head, tail, 2);
insertAtTail(head, tail, 3);
insertAtTail(head, tail, 4);
insertAtTail(head, tail, 5);
insertAtTail(head, tail, 6);
cout <<
"Linked List before appending: "
;
printLinkedList(head);
int
k = 7;
appendAtFront(head, tail, n, k);
cout <<
"Linked List after appending "
<<k<<
" elements: "
;
printLinkedList(head);
}