您的位置:首页 > 其它

LeetCode147: Insertion Sort List

2015-05-04 19:24 399 查看
Sort a linked list using insertion sort.

本题很简单,用插入排序方法对链表进行排序。可以构建一个临时的链表,然后将待排序的链表的每一个节点插入到临时链表中。代码如下:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
		ListNode *insertionSortList(ListNode *head) {
			ListNode tmpNode = ListNode(INT_MIN);
			
			if (head == NULL || head->next==NULL){
				return head;
			}
			while(head){
				ListNode * pNode = head;
				head = head->next;
				ListNode *pPrev  = &tmpNode;
				ListNode *pNext = pPrev->next;
				while (pNext && pNext->val < pNode->val)
				{
					pPrev = pNext;
					pNext = pNext->next;
				}
				pPrev->next = pNode;
				pNode->next = pNext;
			}
			return tmpNode.next;
		}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: