[問題] 環狀鏈結串列合併

看板C_and_CPP作者 (大布丁)時間13年前 (2010/12/31 15:33), 編輯推噓2(209)
留言11則, 7人參與, 最新討論串1/1
小妹我有小小的問題要請教大家,還請各位高手給予指教 開發平台(Platform): (Ex: VC++, Gcc, Linux, ...) cpp 問題(Question): 新增環狀鏈結串列的三個操作函數:複製、反轉環狀串列和『將兩個環狀串列連接起來』 已經做出複製跟反轉,但是不知道要怎麼將兩個串列連接起來 預期的正確結果(Expected Output): 原始的串列:[9][8][7][6][5][4] 反轉後的串列:[4][5][6][7][8][9] 兩個環狀串列連接起來:[9][8][7][6][5][4][4][5][6][7][8][9] 程式碼(Code): (請善用置底文標色功能) #include <stdio.h> #include <stdlib.h> struct list{ int data; struct list *next; }; typedef struct list Node; typedef Node *List; Node *begin=NULL; Node *last=NULL; void createList(int len, int *array) { List last; /* 最後一個節點的指標 */ List newnode; int i; for ( i = 0; i < len; i++ ) { /* 配置節點記憶體 */ newnode = (List) malloc(sizeof(Node)); newnode->data = array[i]; /* 建立節點內容 */ if ( i == 0 ) last = newnode; /* 指向最後一個節點 */ newnode->next = begin; begin = newnode; } last->next = begin; /* 連結第1個節點, 建立環狀串列 */ } void printList() { List current = begin; /* 目前的串列指標 */ do { /* 顯示主迴圈 */ printf("[%d]", current->data); current = current->next; /* 下一個節點 */ } while ( current != begin ); printf("\n"); } Node * reverse(Node * head) { Node *mid_node, *last_node; last=head; mid_node=NULL; while(head!=NULL) { last_node=mid_node; mid_node=head; head=head->next; mid_node->next=last_node; } return(last_node); return(mid_node); } int main(void) { int temp; /* 宣告變數 */ int data[6] = { 4, 5, 6, 7, 8, 9 }; /* 建立串列的陣列 */ List ptr; /* 建立, 走訪與搜尋環狀串列 */ createList(6, data); /* 建立環狀串列 */ printf("原來的串列: "); printList(); /* 顯示串列 */ printf("反轉後的串列:" ); begin=reverse(begin); printList(); system("PAUSE"); return 0; } -- 大布丁 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.131.95.173

12/31 15:49, , 1F
串起來從 createList 去變化就可以了
12/31 15:49, 1F

12/31 16:33, , 2F
那要怎麼串起來?
12/31 16:33, 2F

12/31 19:58, , 3F
reverse 有兩個 return 耶! > " < 把全部的節點都拆掉
12/31 19:58, 3F

12/31 19:58, , 4F
用 createList 把它們一個一個接起來
12/31 19:58, 4F

12/31 21:52, , 5F
單向Linked List會接嗎?
12/31 21:52, 5F

12/31 22:25, , 6F
> < 只要一個迴圈就結束了
12/31 22:25, 6F

12/31 23:36, , 7F
用C++寫類別比較好寫說…。
12/31 23:36, 7F

01/01 00:40, , 8F
01/01 00:40, 8F

01/01 01:53, , 9F

01/01 11:45, , 10F
感謝L大大,在這新年的第一天....幫助了我,小妹我不善言
01/01 11:45, 10F

01/01 11:47, , 11F
詞但很謝謝你,新年愉快
01/01 11:47, 11F
文章代碼(AID): #1D7OSn-i (C_and_CPP)