您的位置:首页 > 理论基础 > 数据结构算法

微软等数据结构+算法面试100题(19)--链表

2012-11-10 13:01 831 查看
链表和数组的区别在哪里?

/*
78.链表和数组的区别在哪里?
分析:主要在基本概念上的理解。
但是最好能考虑的全面一点,现在公司招人的竞争可能就在细节上产生,谁比较仔细,谁获胜的机会就大。

1.数组和链表都是逻辑上线性表。数组在物理上是连续存储的,而链表不是连续的。为了维护链表中元素的线性关系,要依靠指针。
2.数组在定义的时候必须知道大小。数组大小必须在编译时确定。而链表不需要在定义的时候确定大小。
3.由于数组物理上是连续存储的,所以可以实现随即存取。而链表则需要从表头开始逐个遍历要存取的元素。
4.数组要插入一个元素,插入位置后面的所有元素必须向后移动。而链表则不需要做元素移动,只需要修改指针的指向即可。
*/


给定两个单链表(head1, head2),检测两个链表是否有交点,如果有返回第一个交点。

/*
77.关于链表问题的面试题目如下:
2.给定两个单链表(head1, head2),检测两个链表是否有交点,如果有返回第一个交点。
*/

bool IsIntersect(ListNode *head1,ListNode *head2)
{
while(head1->next!=NULL)
head1=head1->next;
while(head2->next!=NULL)
head2=head2->next;
return head1==head2;
}

int ListLen(ListNode *head)
{
int count=0;
while(head->next!=NULL)
{
head=head->next;
count++;
}
return count;
}

ListNode* GetIntersectNode(ListNode *head1,ListNode *head2)
{
assert(head1!=NULL&&head2!=NULL);
ListNode *res=NULL;
if(IsIntersect(head1,head2))
{
int list1len=ListLen(head1);
int list2len=ListLen(head2);
if(list1len-list2len>0)
{
int lendiff=list1len-list2len;
while(lendiff)
{
head1=head1->next;
lendiff--;
}
}
else
{
int lendiff=list2len-list1len;
while(lendiff)
{
head2=head2->next;
lendiff--;
}
}

while(head1!=NULL&&head2!=NULL)
{
if(head1==head2)
res=head1;
}
}
return res;
}


只给定单链表中某个结点p(并非最后一个结点,即p->next!=NULL)指针,删除该结点。

/*
4.只给定单链表中某个结点p(并非最后一个结点,即p->next!=NULL)指针,删除该结点。
*/
void DeleteNode(ListNode *p)
{
ListNode *q=p->next;
p->data=q->data;
p->next=q->next;
}


只给定单链表中某个结点p(非空结点),在p 前面插入一个结点。

/*
5.只给定单链表中某个结点p(非空结点),在p 前面插入一个结点。
*/
void InsertNode(ListNode *p,ListNode *node)
{
node->next=p->next;
p->next=node;
swap(p->data,node->data);
}


给定单链表(head),如果有环的话请返回从头结点进入环的第一个节点。

/*
3.给定单链表(head),如果有环的话请返回从头结点进入环的第一个节点。
*/
ListNode* GetCircleNode(ListNode *head)
{
ListNode *res=NULL;
ListNode *fast=head,*slow=head;
while(fast!=NULL&&fast->next!=NULL)
{
fast=fast->next->next;
slow=slow->next;
if(fast==slow)
break;
}

if(fast!=NULL&&fast->next!=NULL)
{
slow=head;
while(slow!=fast)
{
slow++;
fast++;
}
res=slow;
}
return res;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐