Leetcode 147. Insertion Sort List

Sort a linked list using insertion sort.

题目大意:使用插入排序对一个链表排序。

思路:可以构建一个临时的链表,然后将待排序的链表的每一个节点插入到临时链表中

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     struct ListNode *next;
 6  * };
 7  */
 8 struct ListNode* insertionSortList(struct ListNode* head) {
 9     //如果链表为空或者只有一个节点,则直接返回
10     if(head == NULL || head -> next == NULL)
11             return head;
12     //创建一个头指针
13     struct ListNode* sortedHead = (struct ListNode*)malloc(sizeof(struct ListNode));
14     //初始化头指针的next为NULL
15     sortedHead -> next = NULL;
16     while(head != NULL){
17         //取出原链表的第一个节点,为temp
18         struct ListNode* temp = head;
19         //原链表的头指针指向下一个节点
20         head = head ->next;
21         //接下来查找temp应该插入的位置,从头开始
22         struct ListNode* cur = sortedHead;
23         while(cur -> next != NULL && cur -> next -> val < temp -> val){
24             cur = cur -> next;
25         }
26         temp -> next = cur -> next;
27         cur -> next = temp;
28     }
29     return sortedHead -> next;
30 }
 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode* insertionSortList(ListNode* head) {
12         if(head == NULL || head -> next == NULL)
13             return head;
14         ListNode* sortedHead = new ListNode(-1);
15         while(head != NULL){
16             ListNode* temp = head;
17             head = head ->next;
18             ListNode* cur = sortedHead;
19             while(cur -> next != NULL && cur -> next ->val < temp -> val){
20                 cur = cur -> next;
21             }
22             temp -> next = cur -> next;
23             cur -> next = temp;
24         }
25         return sortedHead -> next;
26     }
27 };

 

posted @ 2016-09-06 11:31  琴影  阅读(174)  评论(0编辑  收藏  举报