匿名使用者
匿名使用者 發問時間: 電腦與網際網路程式設計 · 4 年前

環狀串列(資料結構)~~~急?

請問要怎麼把原本單向串列的建立和刪除function改成環狀的?(如以下

(建立的那邊意思是如果n是5就會自動建立1>2>3>4>5這樣的串列

typedef struct node {

struct node *next; // pointer to left subtree

int value; // node value

}node;

node * create(int n) {

node *head = NULL;

node *temp = NULL;

node *current = NULL;

for (int j = 1; j <= n; j++) {

temp = (node*)malloc(sizeof(node));

temp->value = j;

temp->next = NULL;

if (head == NULL) {

head = temp;

}

else {

current = head;

while (current->next != NULL) {

current = current->next;

}

current->next = temp;

}

}

return head;

}

void delete(node * head,int m) {

node * current, *del;

current = del = head;

for (int i = 1; i < m - 1;i++) {

current = current->next;

}

del = current->next;

current->next = del->next;

free(del);

}

1 個解答

評分
  • 4 年前
    最佳解答

    增加的幫你標上/*new*/

    typedef struct node {

    struct node *next; // pointer to left subtree

    int value; // node value

    }node;

    node * create(int n) {

    node *head = NULL;

    node *temp = NULL;

    node *current = NULL;

    for (int j = 1; j <= n; j++) {

    temp = new node();

    temp->value = j;

    temp->next = NULL;

    if (head == NULL) {

    head = temp;

    }

    else {

    current = head;

    while (current->next != NULL) {

    current = current->next;

    }

    current->next = temp;

    /*new*/if(j==n) temp->next = head;

    }

    }

    return head;

    }

    /*new*/node* mdelete(node * head,int m) {

    node * current, *del;

    current = del = head;

    for (int i = 1; i < m-1 ;i++) {

    current = current->next;

    }

    /*new*/if(m == 1) while (current->next != head) current = current->next;

    del = current->next;

    current->next = del->next;

    /*new*/if(head==del) head = current->next;

    delete(del);

    /*new*/return head;

    }

    void show(node * head){

    node *current = head;

    while (current->next != NULL) {

    cout<<" "<<current->value;

    current = current->next;

    }

    cout<<endl;

    }

還有問題?馬上發問,尋求解答。