1.單鏈表的合併:
合併兩個有序(從小到大)鏈表,首先比較兩鏈表第一個結點值的大小,將小的放入新的鏈表(創建的臨時鏈表);然後將小的那條鏈表向後移動一個位置,重複比較。當然,在進行這些處理之前,先處理空鏈表的情況。
2.單鏈表的排序:
這裏排序方式採用之前熟悉的冒泡排序。
3.單鏈表的翻轉:
對翻轉的要求:遍歷一次。這裏需要三個指針一個指向當前結點,一個指向下一個結點,一個保存翻轉後的鏈表。邏輯代碼裏有註釋。代碼如下
//鏈表的合併,Merge爲遞歸法,Merge2爲非遞歸法
pList Merge(pList l1, pList l2)
{
pList list1 = l1;
pList list2 = l2;
pList newlist = NULL;
if (list1 == NULL )
return list2;
if (list2 == NULL)
return list1;
if ((list1->data) < (list2->data))
{
newlist = list1;
newlist->next = Merge(list1->next, list2);
}
if ((list1->data) > (list2->data))
{
newlist = list2;
newlist->next = Merge(list1, list2->next);
}
return newlist;
}
void Merge2Logic(pList *newlist, pList *list, pList *tmpnode)
{
if (newlist == NULL)
{
newlist = *list;
*list = (*list)->next;
*tmpnode = newlist;
}
else
{
(*tmpnode)->next = *list;
*list = (*list)->next;
*tmpnode = (*tmpnode)->next;
}
}
pList Merge2(pList l1, pList l2)
{
pList list1 = l1;
pList list2 = l2;
pNode tmpnode = NULL;
pList newlist = NULL;
if (list1 == NULL)
return list2;
if (list2 == NULL)
return list1;
while (list1 != NULL && list2 != NULL)
{
if (list1->data >= list2->data)
{
Merge2Logic(&newlist, &list2, &tmpnode);
}
else if (list1->data < list2->data)
{
Merge2Logic(&newlist, &list1, &tmpnode);
}
}
if (list1 == NULL)
tmpnode->next = list2;
if (list2 == NULL)
tmpnode->next = list1;
return newlist;
}
排序代碼
void BubbleSort(pList *pplist)
{
pNode tail = *pplist;
pNode cur = NULL;
int tmp = 0;
if ((*pplist) == NULL || (*pplist)->next == NULL)
return;
while (tail->next != NULL)
{
cur = *pplist;
while ((cur->data) > (cur->next->data))
{
tmp = cur->data;
cur->data = cur->next->data;
cur->next->data = tmp;
cur = cur->next;
if (cur->next == NULL)
{
break;
}
}
tail = tail->next;
}
}
翻轉代碼
void ReverseList(pList *pplist)
{
assert(pplist);
pNode cur = *pplist;
pNode tmp = cur;
pList newlist = NULL;
if((*pplist) == NULL || (*pplist)->next == NULL)
return;
while(cur)
{
tmp = cur;
cur = cur->next;
tmp->next = newlist;
newlist = tmp;
}
*pplist = newlist;
}