c语言 链表笔试题

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

关于链表常考的笔试面试题
1、单链表逆序,在原列表的基础上进行调整
struct ListNode* ReverseList(struct ListNode* pHead )
{
// write code here
//判断第一个元素是否为空,如果为空,则返回NULL;并判断第二个元素是否为空,如果为空,则不需要逆序,直接返回
if(pHead == NULL || pHead->next == NULL) return pHead;
//定义三个节点指针,分别存放前一个操作节点,当前操作节点,下一个操作节点struct ListNode *temp1 = NULL,*temp2 = pHead,*temp3 = pHead->next;
//当下一个操作节点存在时,执行循环,将当前节点的next指向前一个节点,并移动三个指针位置
while(NULL != temp3)
{
temp2->next = temp1;
temp1 = temp2;
temp2 = temp3;
temp3 = temp2->next;
}
//当temp3为空时,说明temp2指向最后一个节点,只需将它的next指向前一个节点temp2->next = temp1;
return temp2;
}
2、找出链表的倒数第n个节点
int query_reverse(List* list,size_t index)
{
Node* f = list->head;
Node* s = list->head;
for(int i=0;i<index;i++)
{
f = f->next;
if(f == NULL) return false;
}
while(f)
{
f = f->next;
s = s->next;
}
return s->data;
3、判断链表中是否有环
bool is_ring(List* list)
{
Node* fast = list->head;//快指针
Node* slow = list->head;//慢指针
while(fast && fast->next)
{
fast = fast->next->next;//快指针每次走两步
slow = slow->next;//慢指针每次走一步
if(slow == fast) return true;//如果相同,则该链表有环}
return false;
}
4、找到环形链表的入口
int ring_in(List* list)
{
if(is_ring)
{
Node* fast = list->head;
Node* slow = list->head;
Node* meet = list->head;
while(fast && fast->next)
{
fast = fast->next->next;
slow = slow->next;
meet = meet->next;
if(slow == fast)
{
slow = list->head;
fast = meet;
fast = fast->next;
slow = slow->next;
if(slow == fast)
return fast->data;
}
}
}
return -1;
}
5、合并两个有序链表,合并后依然有序
List* merge_list(List* list1,List* list2)
{
Node* m = list1->head->next;
Node* n = list2->head->next;
Node* new = create_node();
if(list1 == NULL) return list2;
if(list2 == NULL) return list1;
if(list1== NULL && list2== NULL) return NULL;
while(list1&&list2)
{
if(m->data < n->data)
{
new->next = m;
m = m->next;
}
else
{
new->next = n;
n = n->next;
}
new = new->next;
}
new->next = m?m:n;
return new;
}
6、判断两个链表是否是Y型链表
bool is_y(List* l1,List* l2)
{
int cnt1 = 0,cnt2 = 0;
Node* m = l1->head->next;
Node* n = l2->head->next;
while(m)
{
cnt1++;
m = m->next;
}
while(n)
{
cnt2++;
n = n->next;
}
if(cnt1>cnt2)
{
for(int i=0;i<cnt1-cnt2;i++)
{
m = m->next;
}
}
else
{
for(int i=0;i<cnt2-cnt1;i++)
{
n = n->next;
}
}
while(m == NULL || n = NULL)
{
m = m->next;
n = n->next;
if(m = n) return true;
}
return false;
}。

相关文档
最新文档