笔试面试的时候经常会出现操作链表的题目,一般都会要求直接写代码,所以笔面试之前熟悉一下链表各种操作还是有帮助的,我大概实现了一些一下操作。
一 、先来个最简单的反转链表
void reversal(listNode* head)//reverse the list
{
listNode* before = NULL;
listNode *current = head;
listNode *temp = head;
while(current != NULL)
{
listNode* next = current->next;
current->next = before;
before = current;
current = next;
}
head = before;
}
二、找到链表的中点
listNode* find_mid(listNode* head)
{
listNode* first = head;
listNode* second = head;
while(second != NULL)
{
second = second->next;
if(second != NULL)
{
first = first->next;
second = second->next;
}
}
return first;
}
类似地,还可以实现找到三分之一处节点等等。
三、找到倒数第k个节点
listNode* func(listNode* root, int k)
{
listNode* first = root;
listNode* second = root;
while(k--)
{
if(second != NULL)
second = second->next;
else break;
}
if(second == NULL)
return NULL;
else
{
while(second != NULL)
{
first = first->next;
second = second->next;
}
return first;
}
}
四、判断链表中是否有环
bool judge_circle(listNode* head)
{
listNode* first = head, *second = head;
if(head == NULL) return false;
do
{
second = second->next;
if(second != NULL)
{
first = first->next;
second = second->next;
}
}
while(second != NULL && second != first && first != second);
return first == second;
}
五、1-〉2->3->4->5->6-> 变为 1->6->2->5->3->4(首尾交替取),稍微难的
void reorder()//12345 重排序为15243
{
listNode* current = head;
while(true)
{
listNode* next = current->next;
listNode* findTheEnd = next;
listNode* tempPre = findTheEnd;
if( next == NULL||next->next == NULL )break;
while(findTheEnd->next != NULL)
{
tempPre = findTheEnd;
findTheEnd = findTheEnd->next;
}
tempPre->next = NULL;
current->next = findTheEnd;
findTheEnd->next = next;
current = next;
next = next->next;
}
}