미연시리뷰

os 0-2 1번 임시 swap

두원공대88학번뚜뚜 2020. 10. 2. 18:47

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct node
{
int card;
struct node* next;
struct node* prev;
};

void swap(struct node* a, struct node* b) {
struct node* t;
t = (struct node*)malloc(sizeof(struct node));

*t = *a;
*a = *b;
*b = *t;

b->next = a->next;
a->next = t->next;
b->prev = a->prev;
a->prev = t->prev;

printf("first's next %d prev %d\n", a->next->card, a->prev->card);
printf("next's next %d prev %d\n", b->next->card, b->prev->card);
free(t);
}

int main(void)
{
int num;
scanf_s("%d", &num);

struct node* head = (struct node*) malloc(sizeof(struct node));
head->card = 0;
struct node* tail = (struct node*)malloc(sizeof(struct node));
tail->card = num+1;

head->next = tail;
head->prev = NULL;
tail->next = NULL;
tail->prev = head;

struct node* cur = head;
// printf("%d %d\n", head->card, tail->card);
for (int i = 1; i <= num; i++)
{
struct node* noder = (struct node*) malloc(sizeof(struct node));
noder->card = i;
noder->next = cur->next;
noder->prev = cur;
cur->next->prev = noder;
cur->next = noder;

cur = noder;
}

cur = head->next;
struct node* a = (struct node*)malloc(sizeof(struct node));
struct node* b = (struct node*)malloc(sizeof(struct node));

while (cur->next != NULL)
{
printf("%d ", cur->card);
if (cur->card == 4)
a = cur;
if (cur->card == 2)
b = cur;
cur = cur->next;
}

printf("\n");
cur = head->next;
swap(a, b);

while (cur->next != NULL)
{
printf("%d ", cur->card);
cur = cur->next;
}

return 0;
}list.head.next