</pre><pre name="code" class="cpp">/*
main Definition
Created by taotao man on 2015-10-9
brief: 删除单链表的头元素; 单链表,只是遍历一次,求出中间节点
// 修改记录:
add SetA();
Change GetA();
*/
#include "stdio.h"
#include <iostream>
typedef struct student
{
int data;
struct student *next;
}node;
node *creat()
{
node *head, *s, *p;
p = (node*)malloc(sizeof(node));
/*p = head;*/
head = p;
int cycle = 1, x;
while(cycle)
{
printf("\n please input the data:");
scanf("%d", &x);
if(x != 0)
{
s = (node*)malloc(sizeof(node));
s->data = x;
p->next = s;
p = s;
}
else
cycle = 0;
}
p->next = NULL;
head = head->next;
printf("\n 头指针是:%d", head->data);
return head;
}
node *RemoveHead(node *head) // 删除单链表的头元素
{
node *p;
p = head;
head = head->next;
free(p);
return head;
}
void searchmid(node *head) // 单链表,只是遍历一次,求出中间节点
{
node *temp = head;
while((head) || (head->next->next != NULL))
{
head = head->next->next;
printf("\n ahui: %d", head->data);
temp = temp->next;
}
printf("\n 中间节点的数据是: %d", temp->data);
}
void main()
{
node *sjt = creat();
/*sjt = RemoveHead(sjt);
printf("\n 删除单链表的头元素后,头结点是:%d", sjt->data);
*/
searchmid(sjt);
system("pause");
}
//
其实说白了,就是设立两个指针,当第一个指针p,每次移动两个位置,即p = p -> next -> next,q每次移动一个位置,即q = q -> next。
当p到达最后一个节点的时候,q就是中间节点了。
void searchmid(node * head, node *mid)
{
node *temp = head;
while(head -> next->next != null)
{
head = head->next->next;
temp = temp->next;
mid = temp;
}
}