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

2017-07-21 4:32 pm
請問要怎麼把原本單向串列的建立和刪除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)

2017-07-21 5:37 pm
✔ 最佳答案
增加的幫你標上/*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;

}


收錄日期: 2021-05-04 02:23:51
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20170721083245AAQZF3i

檢視 Wayback Machine 備份