求链表的中间结点

求链表的中间结点,如果链表长度为奇数,则返回中间结点,如果链表长度为偶数,则返回中间两个结点的任意一个。

(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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值