【数据结构】给出一个链表,遍历一次就找到中间节点

</pre><pre name="code" class="plain"><span style="font-family: Arial, Helvetica, sans-serif;"><pre name="code" class="cpp">// 13_1_7.cpp : Defines the entry point for the console application.</span>
//

#include "stdafx.h"
#include <stdio.h>  
#include <conio.h>  
#include <string.h>  
#include <iostream>  
using namespace std;

typedef struct student
{
	int data;
	struct student *next;
}node;

node *create()
{
	node *p1, *p2, *head;
	int cycle = 1, x;
	head = (node*)malloc(sizeof(node));
	p1 = head;
	while (cycle)
	{		
		cout << "please input an integer: ";
		cin >> x;
		if (x != 0)
		{
			p2 = (node*)malloc(sizeof(node));
			p2->data = x;
			p1->next = p2;
			p1 = p2;
		}

		else
		{
			cycle = 0;
		}
	}
	head = head->next;
	p1->next = NULL;
	return head;
}

void findmid(node* head)
{
	node *p1, *p2, *mid;
	p1 = head;
	p2 = head;

	while (p1->next->next != NULL)
	{	
		p1 = p1->next->next;
		p2 = p2->next;
		mid = p2;
	}	
}

void print(node *head)
{
	node *p;
	if (head != NULL)
	{
		p = head;
		while (p != NULL)
		{
			cout << p->data << endl;
			p = p->next;
		}
	}
}

int _tmain()
{
	node *link_list = create();
	printf("The original link list is:\n");
	print(link_list);
	findmid(link_list);
	return 0;
}

给出一个链表,遍历一次就找到中间节点

设置两个指针,一个每次移动两个位置,一个每次移动一个位置,当第一个指针到达尾节点时,第二个指针就达到了中间节点的位置

处理链表问题时,”快行指针“是一种很常见的技巧,快行指针指的是同时用两个指针来迭代访问链表,只不过其中一个比另一个超前一些。快指针往往先行几步,或与慢指针相差固定的步数。

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值