几天不写博文,发现就生疏了。
今天写个有关链表的排序。我觉得这个可以和数组对着看。
直接贴别人的链接。借鉴了http://getpocket.com/a/read/709284107的博客。
插排,我觉得按照算法导论上的思路来写,才是金典的。
#include <iostream>
using namespace std;
struct ListNode
{
int m_nValue;
ListNode *m_pNext;
};
ListNode* insertList(ListNode *L1)
{
ListNode *pStart = new ListNode();
pStart->m_pNext = L1;
ListNode *pCur = L1->m_pNext;
ListNode *pEnd = L1;
while(pCur)
{
ListNode *pre = pStart;
ListNode *tmp = pStart->m_pNext;
while((tmp != pCur) && (tmp->m_nValue<pCur->m_nValue))
{
tmp=tmp->m_pNext; pre=pre->m_pNext;
}
if(tmp==pCur)pEnd = pCur;
else
{
pEnd->m_pNext = pCur->m_pNext;
pCur->m_pNext = tmp;
pre->m_pNext = pCur;
}
pCur = pEnd->m_pNext;
}
L1 = pStart->m_pNext;
delete pStart;
pStart = NULL;
return L1;
}
void createList(ListNode **L1, int value)
{
ListNode *p = new ListNode;
p->m_nValue = value;
p->m_pNext = NULL;
if(*L1 == NULL)
{
*L1 = p;
}
else
{
ListNode *q = *L1;
while(q->m_pNext)
{
q = q->m_pNext;
}
q->m_pNext = p;
}
}
void printList(ListNode *l)
{
if(l == NULL)
printf("NULL\n");
else
{
ListNode * pCur = l;
while(pCur != NULL)
{
//这里主要时要注意输出的格式
if(pCur->m_pNext == NULL)
printf("%d\n",pCur->m_nValue);
else
printf("%d ",pCur->m_nValue);
pCur = pCur->m_pNext;
}
}
}
int main()
{
ListNode *head1 = NULL;
ListNode *head2 = NULL;
createList(&head1, 12);
createList(&head1, 3);
createList(&head1, 5);
createList(&head1, 6);
createList(&head1, 9);
createList(&head1, 11);
printList(head1);
/*createList(&head2, 4);
createList(&head2, 7);
createList(&head2, 8);
createList(&head2, 10);
createList(&head2, 12);
createList(&head2, 13);
printList(head2);*/
head2 = insertList(head1);
printList(head2);
}
为了对比,我再写个数组的插排:
void insert(int *A, int len)
{
if(A==NULL||len<=0)
return;
int i = 1;
while(i<len)
{
int key = A[i];
int j= i-1;
while((j>=0)&&A[j]>key)
{
A[j+1] = A[j];
j--;
}
A[j+1] = key;
i++;
}
}
两点注意:
1.第二个while。数组的比较是找到比自己大的节点。而链表是找到比它小的节点。其实也是正常的,因为链表是从头开始,数组是从末尾开始的。
2.链表的pStart的设置,是为了节省判断开头的复杂。