基础算法(三)反转一个单向循环链表
翻转一个链表需要三个指针:
一个保存后面的结点地址
一个保存当前要改变指向的结点的地址
一个保存前面的结点地址
//翻转单向循环链表
void link_reverse(link *head)
{
link *prev = head;
link *temp = prev->next;
link *front;
while(temp != head)
{
front = temp->next;
temp->next = prev;
prev = temp;
temp = front;
}
head->next = prev; //最后让head->next指向原来最后的结点
return;
}
那翻转的是单向链表呢?
struct ListNode* ReverseList(struct ListNode* pHead )
{
struct ListNode*prev = NULL;
struct ListNode*temp = pHead;
struct ListNode*front = NULL;
while(temp != NULL)
{
front = temp->next;
temp->next = prev;
prev = temp;
temp = front;
}
pHead->next = prev; //最后让head->next指向原来最后的结点
return pHead;
}