Fast location to the middle of a single linked list of nodes __ data structure
Source: Internet
Author: User
#include <stdio.h>
#include <malloc.h>
typedef struct NODE
{
int data;
struct Node *next;
}node,*linkedlist;
/*
The following procedure establishes a single linked list for the tail difference method
*/
void Tailcreat (LinkedList &l,int i)
{
Int J;
LinkedList p1,p2;
L = (linkedlist) malloc (sizeof (Node));
P1=l;
for (j=1;j<=i;j++)
{
P2= (LinkedList) malloc (sizeof (Node));
p2->data=j;
p1->next=p2;
P1=P2;
}
p1->next=null;
}
/*
Delete a single linked list
*/
void Remove (LinkedList &l)
{
LinkedList p,q;//p is the node that is currently being deleted, if he is deleted. We also want to delete his next node. Because P is no longer here, so at this point,
We need to use Q to record the next node of P.
p=l->next;
while (p)
{
q=p->next;
Free (p);
p=q;
}
l->next=null;
}
/*
Quickly navigate to the middle node of a single linked list
Defines a quick pointer search and a slow pointer middle. Fast each step two steps, slow each time take one step. When the fast to the end of the time, slowly just go to the middle.
*/
int Middle (linkedlist l,int *e)
{
LinkedList Search,middle;
Search=middle=l;
while (Search->next!=null)
{
if (search->next->next!=null)
{
search=search->next->next;
middle=middle->next;
}
Else
{
search=search->next;
}
}
*e=middle->next->data;
return 1;
}
int main ()
{
int e;
LinkedList l,p;
Tailcreat (l,9);
printf ("%d\n", l->next->data);
p=l->next;
while (p!=null)//View all the elements in the list
{
printf ("%d", p->data);
p=p->next;
}
printf ("\ n");
Middle (l,&e);
printf ("%d\n", e);
Remove (L);
printf ("%d\n", l->next->data);//The program cannot run at this time because the L-next is empty,
return 1;
}
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.