Untitled
unknown
plain_text
4 years ago
2.9 kB
6
Indexable
#include<stdio.h>
#include<stdlib.h>
typedef struct _Node//doubly-linked lists.
{
char chr;
struct _Node *prev;
struct _Node *next;
}Node;
// Delete the given node, and move its original
// pointer to the previous node if it exists.
void back(Node **ptrNode)
{
Node *curNode=*ptrNode;//*******
if(curNode->prev == NULL) return;// Don't do anything with the dummy head.
if(curNode->next == NULL)// Deleting the last node of the list.
{
(*ptrNode)=curNode->prev;
(*ptrNode)->next=NULL;
free(curNode);//*******
}
else// Deleting nodes in the middle section of the list.
{
curNode->next->prev=curNode->prev;
curNode->prev->next=curNode->next;
(*ptrNode) = curNode->prev;//********
free(curNode);
}
}
// Insert a node right before the given node,
// and make its original pointer point to the new node.
void insert(Node **ptrNode,char input)
{
Node *curNode=*ptrNode;
Node *newNode=(Node*)malloc(sizeof(Node));
newNode->chr=input;
newNode->next=curNode->next;
newNode->prev=curNode;
if(curNode->next != NULL)// This won't be run if the new node is on the far right of the list.
curNode->next->prev=newNode;
curNode->next=newNode;
(*ptrNode) = newNode;
}
// Print all nodes from left to right
// and delete them along the way.
void print(Node *head)
{
Node *curNode=head->next;
while (curNode != NULL)
{
printf("%c",curNode->chr);
Node *temp=curNode;
curNode=curNode->next;
free(temp);
}
free(head);
printf("\n");
}
int main()
{
int T,N;
scanf("%d\n",&T);
while (T--)
{
Node *head=(Node*)malloc(sizeof(Node));//// The head is a dummy node with no data.
head->prev=NULL;// It's the only node whose prev points to NULL.
head->next=NULL;
Node *curNode=head;// curNode is used as a cursor.
scanf("%d\n",&N);
while (N--)
{
char input=getchar();
switch (input)
{
case 'L':// Move cursor one node to the left. (prev)
if(curNode->prev != NULL)
curNode=curNode->prev;
break;
case 'R':// Move cursor one node to the right. (next)
if(curNode->next != NULL)
curNode=curNode->next;
break;
case 'B': // Backspace.
if(curNode->prev != NULL)
back(&curNode);
break;
default: // Insert char.
insert(&curNode,input);
break;
}
}
print(head);// Print and free all nodes.
}
return 0;
}
Editor is loading...