求链表的中间结点,如果链表长度为奇数,则返回中间结点,如果链表长度为偶数,则返回中间两个结点的任意一个。
(1)定义两个指针,同时从头结点出发。
(2)指针p1一次走2步,指针p2一次走1步。
(3)当p1走到链表末尾的时候,p2正好在链表中间。
struct node
{
int value;
node* next;
};
/* 链表尾加入新元素*/
node* addNode(node*head ,int addValue)
{
node* newNode=new node();
newNode->next=NULL;
newNode->value=addValue;
node* p=new node();
p=head; //list的头结点
if(head==NULL)
{
head=newNode; //新节点为链表头节点
}else
{
while(p->next!=NULL)//找到尾节点
p=p->next;
p->next=newNode; //在尾节点后面加入新节点
}
return head;
}
/*找出链表中间结点*/
node* findMiddleNode(node* head)
{
node* pNode1=head;
node* pNode2=head;
if(head==NULL)return NULL ;//链表为空
if(head->next==NULL||head->next->next==NULL) return head;//链表只有一个或者两个结点
while(pNode1->next!=NULL&&pNode1->next->next!=NULL)//链表长度是奇数的时候,临界条件p->next==null;
{
pNode1=pNode1->next->next;//每次走2个结点
pNode2=pNode2->next;//每次走1个结点
}
return pNode2;
}