二、链表
首先定义链表节点结构体
typedef struct _node
{
int value;
_node* next;
}Node,*ListNode;
1、逆序(剑指offer 113页)
ListNode reverseList(ListNode head)
{
if(head == NULL || head->next == NULL || head->next->next ==NULL)
return head;
//最简单的思路,遍历之后的元素,倒序插入即可
ListNode curr = head->next->next;
head->next->next = NULL;
while(curr != NULL)
{
ListNode next = curr->next;
curr->next = head->next;
head->next = curr;
curr = next;
}
return head;
}
2、删除节点
时间为O(1),要考虑三种情况:删除结点为头结点、删除结点为尾结点、删除节点为中间结点。(剑指offer 100页)
//删除list中指定节点,这里已知待删除节点的地址node
void deleteNode(ListNode head, ListNode node)
{
//要求时间复杂度为O(1)
//在删除节点时,需要了解其前一个节点的地址,这里可以换个角度考虑将待删除节点后续节点的值复制到待删除节点
//删除其后续节点,则可以在O(1)时间复杂度下完成任务
//在没有后续节点的情况下,如何处理?将第一个节点内容复制给node节点,同时删除第一个节点
if(head == NULL || node == NULL)
return;
if(node->next != NULL)
{
ListNode follow = node->next;
node->value = follow->value;
node->next = follow->next;
delete follow;
}
else
{
ListNode first = head->next;
node->value = first->value;
head->next = first->next;
delete first;
}
}
3、在一定限制条件操作
(1)输出链表中倒数第K个结点。(剑指offer108页)
//输出倒数第K个元素,
//最简单的思路,设定两个指针进行遍历,第一个指针先行出发k步,之后两个指针同时前进
//当第一个指针指向尾端是,第二个指针指向的即为倒数第K个元素位置
void outputK(ListNode head,int k)
{
if(head== NULL)
{
cout<<"给定链表为空"<<endl;
return;
}
ListNode first = head->next;
ListNode second = head->next;
int count = 0;
while(count < k)
{
first = first->next;
count++;
if(first == NULL)
{
cout<<"给定链表中不存在K个元素"<<endl;
return;
}
}
while(first!=NULL)
{
second = second->next;
first = first->next;
}
cout<<"倒数第K个元素的值为"<<second->value<<endl;
}
(2)判断链表是否有环
//判断链表是否含有环,最简单的思路,使用两个指针,一快一慢,如果快的落在慢的之后,说明存在环
bool haveCircle(ListNode head)
{
if(!head) return false;;
ListNode fast = head->next;
ListNode slow = head->next;
while(fast != NULL && slow != NULL)
{
if(fast < slow)
return true;
slow = slow->next;
fast = fast->next;
if(fast != NULL)
fast = fast->next;
else
return false;
}
return false;
}
(3)判断二个链表是否相交
//判断二个链表是否相交
bool haveCross(ListNode first,ListNode second)
{
//最简单的思路便是遍历到最后,节点地址是否相同,这样需要进行两次遍历,时间复杂度为O(n)
//前提两链表均为无环
if (first == NULL || second ==NULL)
return false;
ListNode firstCur = first;
ListNode secondCur = second;
while(firstCur->next != NULL)
firstCur = firstCur->next;
while(secondCur->next != NULL)
secondCur = secondCur->next;
if(firstCur == secondCur)
return true;
else
return false;
}
(4)求链表的中间结点
ListNode findMid(ListNode head)
{
//设定两个指针,一个一次走两步,一个一次走一步,前者到达末尾是,后者恰好走到终点位置
if(!head) return NULL;
ListNode first = head->next;
ListNode second = head->next;
while(first != NULL)
{
second = second->next;
first = first->next;
if(first != NULL)
first = first->next;
}
return second;
}
复杂链表的复制(优酷土豆笔试题)
未解答,待补充