一、快速找到链表的中间节点
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;
}