C 雙向鏈表的簡單排序實現

來源:互聯網
上載者:User

標籤:問題   表頭   一點   next   實現   name   last   c結構體   方法   

今天偶爾看到了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方法可以實現的簡單一點,因為只會交換相鄰的兩個節點。

我這樣寫就是要更一般化,對節點操作要求更高,利於自己理解。

 

C 雙向鏈表的簡單排序實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.