您的位置:首页 > 职场人生

链表常见面试题

2013-05-09 22:19 302 查看
一、头文件

#ifndef LISTUTILS_H
#define LISTUTILS_H

typedef int ElemType;

typedef struct _node
{
ElemType data;
struct _node *next;
} Node;

/*
Description: get the intersection point of two list
Param:       headA: header of list1
headB: header of list2
Return:      the intersection point or null for none
*/
const Node *GetIntersectionPoint(const Node *headA, const Node *headB);

/*
Description: reverse the given list
Param:       head: header of list
Return:      none
*/
void ReverseList(Node *head);

/*
Description: get the circle point of list
Param:       head: header of list
Return:      the circle point or null for none
*/
const Node *GetCirclePoint(const Node *head);

void PrintList(Node *head);
#endif // LISTUTILS_H


二、C文件

#include <stdio.h>
#include "ListUtils.h"

const Node *GetIntersectionPoint(const Node *headA, const Node *headB)
{
const Node *tmpA, *tmpB;
unsigned int lenA = 0, lenB = 0, i;

if(NULL == headA || NULL == headB || NULL == headA->next || NULL == headB->next){
return NULL;
}

tmpA = headA;
//make tmpA points to the end of headA
while(NULL != tmpA->next){
tmpA = tmpA->next;
++lenA;
}

tmpB = headB;
//make tmpB points to the end of headB
while(NULL != tmpB->next){
tmpB = tmpB->next;
++lenB;
}

//no intersection point
if(tmpA != tmpB){
return NULL;
}

tmpA = headA->next;
tmpB = headB->next;
if(lenA > lenB){
for(i = 0; i < lenA - lenB; ++i){
tmpA = tmpA->next;
}
}else if(lenB > lenA){
for(i = 0; i < lenB - lenA; ++i){
tmpB = tmpB->next;
}
}

while(tmpA != tmpB){
tmpA = tmpA->next;
tmpB = tmpB->next;
}

return tmpA;
}

const Node *GetCirclePoint(const Node *head)
{
Node *fast = NULL;
Node *slow = NULL;
Node *circlePoint  = NULL;

//empty list
if(NULL == head || NULL == head->next){
return NULL;
}

fast = slow = head->next;
while(fast && fast->next){
fast = fast->next->next;
slow = slow->next;
if(fast == slow){
circlePoint = fast;
break;
}
}

//no circlePoint
if(NULL == circlePoint){
return NULL;
}

fast = head->next;
while(fast != slow){
fast = fast->next;
slow = slow->next;
}

return fast;
}

void ReverseList(Node *head)
{
Node *first, *second, *third;

//if there is less than one node, return
if(NULL == head || NULL == head->next){
return;
}

first = head->next;
second = first->next;
first->next = NULL;
while(second){
//cache the next node of "second"
third = second->next;
//insert the "second" node to the front of result list
second->next = first;
//move the first node to point to "second"
first = second;
//restore the "second" node
second = third;
}

head->next = first;

return;
}

void PrintList(Node *head)
{
Node *node;
int pos = -1;
if(NULL == head)
{
return;
}
node = head->next;
while(node)
{
printf("[%d]----[%d]\n", ++pos, node->data);
node = node->next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: