您的位置:首页 > 编程语言 > C语言/C++

链表的笔试题

2016-01-04 19:58 344 查看
单向链表节点定义

typedef struct node
{
int data;
struct node *next;
}Node,*pNode;
双向链表节点定义

typedef struct node
{
int data;
struct node *next;
struct node *pre;
}Node,*pNode;


链表逆序

非递归方法:

pNode RevertList(pNode head)
{
if ((head == NULL) || (head->next == NULL))
return head;
pNode p1 = head;
pNode p2 = p1->next;
pNode p3 = p2->next;
p1->next = NULL;
while(p3 != NULL)
{
p2->next = p1;
p1 = p2;
p2 = p3;
p3 = p3->next;
}
p2->next = p1;
head = p2;
return head;
}
递归方法:

pNode RevertList(pNode head)
{
pNode p1 = NULL;
if ( (head == NULL) || (head->next == NULL))
return head;

p1 = RevertList(head->next);
head->next->next = head;
head->next = NULL;
return p1;
}

将2个有序的链表合并成一个有序链表

非递归方法:

pNode MergeList(pNode head1, pNode head2)
{
if (head1 == NULL)
return head2;
if (head2 == NULL)
return head1;

pNode p1 = NULL;
pNode p2 = NULL;
pNode head = NULL;
if (head1->data < head2->data)
{
head = head1;
p1 = head1->next;
p2 = head2;
}
else
{
head = head2;
p1 = head1;
p2 = head2->next;
}
pNode curNode = head;
while((p1 != NULL) && (p2 != NULL))
{
if (p1->data < p2->data)
{
curNode->next = p1;
curNode = p1;
p1 = p1->next;
}
else
{
curNode->next = p2;
curNode = p2;
p2 = p2->next;
}
}
if (p1 == NULL)
curNode->next = p2;
else
curNode->next = p1;

return head;
}
递归方法:

pNode MergeList(pNode head1, pNode head2)
{
if (head1 == NULL)
return head2;
if (head2 == NULL)
return head1;

pNode head = NULL;
if (head1->data < head2->data)
{
head = head1;
head->next = MergeList(head1->next, head2);
}
else
{
head = head2;
head->next = MergeList(head1, head2->next);
}
return head;
}

判断一个单链表是有环的

bool CheckLoop(const pNode head)
{
if (head == NULL)
return false;
pNode low = head;
pNode fast = head->next;

while((fast != NULL) && (fast->next != NULL))
{
if (low == fast)
return true;
low = low->next;
fast = fast->next->next;
}
return false;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ 链表 笔试题