[小算法] 找出单链表中的中间元素
2012-04-18 18:04 Kevin Pan 阅读(444) 评论(0) 编辑 收藏 举报两种情况:
1. 链表有奇数个结点, 中间元素只有一个;
2. 链表有偶数个结点, 中间元素会有两个;
#include "stdafx.h"
#include <iostream>
using namespace std;
struct Link
{
int Data;
Link *Next;
};
void PrintMiddleNode(Link *head);
int _tmain(int argc, _TCHAR* argv[])
{
struct Link head, node1,node2,node3,node4,node5;
head.Data = -1;
head.Next = &node1;
node1.Data = 1;
node1.Next = &node2;
node2.Data = 2;
node2.Next = &node3;
node3.Data = 3;
node3.Next = &node4;
node4.Data = 4;
node4.Next = &node5;
node5.Data = 5;
node5.Next = NULL;
PrintMiddleNode(&head);
cout << endl;
cin.get();
return 0;
}
void PrintMiddleNode(Link *head)
{
if(head == NULL || head->Next == NULL) return;
Link *singleStepPointer = head;
Link*doubleStepPointer = head;
while(true)
{
if(doubleStepPointer->Next != NULL)
{
doubleStepPointer = doubleStepPointer->Next;
if(doubleStepPointer->Next != NULL)
{
doubleStepPointer = doubleStepPointer->Next;
}
else//奇数个
{
//middle node should be singleStepPointer->Next
cout << "Middle node is: " << singleStepPointer->Next->Data;
break;
}
}
else//偶数个
{
//middle nodes should be current singleStepPointer and singleStepPointer->Next
cout << "Middle nodes are: " << singleStepPointer->Data << " and " << singleStepPointer->Next->Data;
break;
}
singleStepPointer = singleStepPointer->Next;
}
}
#include <iostream>
using namespace std;
struct Link
{
int Data;
Link *Next;
};
void PrintMiddleNode(Link *head);
int _tmain(int argc, _TCHAR* argv[])
{
struct Link head, node1,node2,node3,node4,node5;
head.Data = -1;
head.Next = &node1;
node1.Data = 1;
node1.Next = &node2;
node2.Data = 2;
node2.Next = &node3;
node3.Data = 3;
node3.Next = &node4;
node4.Data = 4;
node4.Next = &node5;
node5.Data = 5;
node5.Next = NULL;
PrintMiddleNode(&head);
cout << endl;
cin.get();
return 0;
}
void PrintMiddleNode(Link *head)
{
if(head == NULL || head->Next == NULL) return;
Link *singleStepPointer = head;
Link*doubleStepPointer = head;
while(true)
{
if(doubleStepPointer->Next != NULL)
{
doubleStepPointer = doubleStepPointer->Next;
if(doubleStepPointer->Next != NULL)
{
doubleStepPointer = doubleStepPointer->Next;
}
else//奇数个
{
//middle node should be singleStepPointer->Next
cout << "Middle node is: " << singleStepPointer->Next->Data;
break;
}
}
else//偶数个
{
//middle nodes should be current singleStepPointer and singleStepPointer->Next
cout << "Middle nodes are: " << singleStepPointer->Data << " and " << singleStepPointer->Next->Data;
break;
}
singleStepPointer = singleStepPointer->Next;
}
}