今天偶爾看到了C結構體的單項鏈表。
於是重新溫習了下雙向鏈表,重寫了下雙向鏈表的簡單排序實現,當做溫習總結吧。
先定義雙向鏈表
1 struct Student{ 2 int studentId; 3 char * name; 4 Student *next, *last; 5 };
然后就是關鍵的排序方法:
int sortByName(Student *p){ Student *head = p; //從鏈表頭部開始排序(也可以去掉,去掉的話就是從傳入的節點開始排序) while(head->last != NULL){ head = head->last; } while(head != NULL){ Student *headNext = head->next; while(headNext != NULL){ if(strcmp(head->name, headNext->name) > 0){ swapStudent(head, headNext); //注意這里一定要交換下,因為改了鏈表節點的位置 Student *tmp = head; head = headNext; headNext = tmp; } headNext = headNext->next; } head = head->next; } return 1; }
里面又涉及到一個swapStudent方法,這個方法實現交換兩個節點的功能
代碼如下:
void swapStudent(Student *s1, Student *s2){ if(s1->next == s2){ if(s2->next != NULL){ s2->next->last = s1; } if(s1->last != NULL){ s1->last->next = s2; } s1->next = s2->next; s2->last = s1->last; s1->last = s2; s2->next = s1; }else if(s1->last == s2){ if(s1->next != NULL){ s1->next->last = s2; } if(s2->last != NULL){ s2->last->next = s1; } s2->next = s1->next; s1->last = s2->last; s2->last = s1; s1->next = s2; }else{ //這里面一定要注意更新節點相鄰節點里面的上下節點的值 //我被坑在這,查了好久才查出來 //上面兩個循環體也一樣需要注意 if(s1->next != NULL){ s1->next->last = s2; } if(s1->last != NULL){ s1->last->next = s2; } if(s2->next != NULL){ s2->next->last = s1; } if(s2->last != NULL){ s2->last->next = s1; } Student *s1Next = s1->next; Student *s1last = s1->last; s1->next = s2->next; s1->last = s2->last; s2->next = s1Next; s2->last = s1last; } }
上面就是簡單排序實現的核心實現。
如果仔細看了的話,會注意一個問題。
如果使用冒泡排序,上面的swap方法可以實現的簡單一點,因為只會交換相鄰的兩個節點。
我這樣寫就是要更一般化,對節點操作要求更高,利於自己理解。