迴圈連結串列(C語言)
阿新 • • 發佈:2020-09-20
struct Node { int data; Node* next; }; struct Node* circlecreate(void) {//建立雙向連結串列 struct Node* head; head = (Node*)malloc(sizeof(Node)); head->next = head;//只有一個元素,所以首尾相連 head->data = 0; return head; }
二:插入操作(刪除操作跟其類似)
int insert_node(Node* head, intnum) { Node* new_node = NULL; struct Node* temp = head; new_node = (Node*)malloc(sizeof(Node)); if (!new_node) { return -1; } new_node->data = num; //除了使用for來迴圈遍歷,也可以使用while來遍歷,只不過用for的會有元素個數 while (temp->next) { temp = temp->next; } temp->next = new_node; new_node->next = temp; return 0; }
三:遍歷雙向連結串列:
int show_list(struct Node* head) { Node* temp = head->next; if (temp->next == head)//判斷是不是隻有一個元素,因為只有這種情況才會有if中的這種情況 return -1; while (temp != head) temp = temp->next; return 0; }