一、快速找到鏈表的中間節點
1、常規方法:遍歷所有節點L,找到中間 L/2,遍歷L/2, 搞定。
2、較快速 : fast和slow都指向頭,fast每次跳2個node,slow跳1個,當fast跳到尾的時候,slow就是中間。
{
slow = head;
fast = head;
/*暫時沒有考慮循環鏈表情況*/
while( (NULL != fast) && (NULL != (fast->next)) )
{
fast = fast->next->next;
/*當爲偶數時,返回前一個,若要返回後一個,則去掉該if*/
if (NULL == fast)
return slow;
slow = slow->next;
}
return slow;
}
二、判斷一個鏈表有循環
1、“O” 型
(1)記錄一個 node的地址,然後遍歷整個鏈表(步長可爲1,也可爲2),與這個地址對比。
2、“6” 型
(1)定義兩個指針slow,fast,指向同一node,slow步長爲1,fast步長爲2,進行遍歷;
(2)當出現 fast == slow時,說明存在循環。
P.S:可聯想操場賽跑,只要一直跑,快的一定會和慢的再相逢;此方法也適用於“O”型。
{
int iCycleFlag = 0;
slow = nodeA;
fast = nodeA;
while( (NULL != fast) && (NULL != (fast->next)) )
{
fast = fast->next->next;
slow = slow->next;
if (fast == slow)
{
iCycleFlag = 1;
break;
}
}
return iCycleFlag;
}
三、鏈表的逆序
1、畫個鏈表圖,揣摩一下,先暫存->next下一節點到tmp(爲了遍歷),再操作->next(改變指向)
再保存一下上一個節點。(2015.4.13.18.50)
typedef struct node
{
struct node *next;
int id;
} NODE_T;
NODE_T * list_reser(NODE_T *psthead)
{
NODE_T *pstnode = psthead;
NODE_T *pstmp = NULL;
NODE_T *lastnode = NULL;
while (NULL != pstnode)
{
/*暫存下一個 節點*/
pstmp = pstnode->next;
pstnode->next = lastnode;
lastnode = pstnode;
pstnode = pstmp;
}
/*返回原尾節點,也就是現在的頭結點*/
return lastnode;
}