如何修复双向链接的节点无法正确链接?

时间:2019-04-24 01:20:59

标签: c

我的双向链表是一副纸牌。我已经正确初始化了它们,但是它们没有连接。左侧标头在两个方向上均指向NULL,而我右侧标头的上一个指针指向前一张卡,而该卡的上一个指针则指向NULL。如何连接它们?我很确定这不是一个困难的解决方案,但由于某种原因我无法弄清楚。

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<math.h>
#include<string.h>
#include <stdlib.h>
#define RAND_MAX 51

typedef struct card_s {
char suit;
int face;
struct card_s *next, *previous;
}card;

void addcard(card *p, card **hl, card **hr, int i, char c) {
card *temp;
temp = (card *)malloc(sizeof(card)); 
temp->face = i;
temp->suit = c;
if (*hl == NULL) {
    temp->previous = NULL;
    temp->next = NULL;
    *hl = temp;
    *hr = temp;
}
else if (p == NULL) {
    p = calloc(1, sizeof(card));
    temp->previous = p;
    temp->next = NULL;
    p->next = temp;
    *hr = temp;
}
else {
    temp->next = p->next;
    temp->previous = p;
    p->next = temp;
    temp->next->previous = temp;
}
}

void delectecard(card *p, card **hl, card **hr) {
if (p == *hl) {
    *hl = p->next;
}
else {
    p->previous->next = p->next;
}
if (p == *hr) {
    *hr = p->previous;
}
else {
    p->next->previous = p->previous;
}
free(p);
}
void createdeck(card *p, card **hl, card **hr) {
int i = 1;
int j;
while (i <= 13) {
    j = 1;
    while (j <= 4) {
        if (j == 1) {
            addcard(p, hl, hr, i, 'S');
        }
        if (j == 2) {
            addcard(p, hl, hr, i, 'H');
        }
        if (j == 3) {
            addcard(p, hl, hr, i, 'D');
        }
        if (j == 4) {
            addcard(p, hl, hr, i, 'C');
        }j++;
    }
    i++;
}
}
void printdeck(card *currentNode) {
while (currentNode != NULL) {
    printf("Face: %d, Suit: %c\n", currentNode->face, currentNode- 
 >suit);
    currentNode = currentNode->next;
}
}
 int main(void) {
card *headl = NULL, *headr = NULL;
createdeck(headr, &headl, &headr);
printdeck(headl);
 }

0 个答案:

没有答案