DSA P2 3
unknown
plain_text
2 years ago
1.7 kB
13
Indexable
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
typedef struct node
{
int val;
struct node* prev;
struct node* next;
} Node;
Node* genNode(int val, Node* prev, Node* next)
{
Node* node = (Node*)malloc(sizeof(Node));
node->val = val;
node->prev = prev;
node->next = next;
return node;
}
void printList(Node* head, Node* tail)
{
Node* cur = head;
printf("normal:\n");
while (cur != NULL)
{
printf("%d ", cur->val);
cur = cur->next;
}
printf("\nreverse:\n");
cur = tail;
while (cur != NULL)
{
printf("%d ", cur->val);
cur = cur->prev;
}
printf("\n");
}
int main()
{
int numNodes;
scanf("%d", &numNodes);
Node* head = genNode(0, NULL, NULL);
Node* cur = head;
for (int i = 0; i < numNodes; i++)
{
int value;
scanf("%d", &value);
cur->val = value;
cur->next = genNode(0, NULL, NULL);
cur->next->prev = cur;
cur = cur->next;
}
Node* tail = cur->prev;
tail->next = NULL;
printList(head, tail);
int k;
scanf("%d", &k);
Node* newHead = tail;
Node* prevNode = tail;
for (int i = 0; i < k; i++)
{
cur = prevNode;
prevNode = cur->prev;
cur->prev = cur->next;
cur->next = prevNode;
}
if (prevNode != NULL)
prevNode->next = NULL;
if (k != numNodes)
{
tail = prevNode;
cur->next = head;
head->prev = cur;
}
else
{
tail = cur;
}
head = newHead;
printList(head, tail);
return 0;
}Editor is loading...
Leave a Comment