Determine whether a one-way linked list has loops and

Source: Internet
Author: User

Determine whether a one-way linked list has loops and

1. Set up two pointers, I, and j points to the header node.

2. I take step 1 and step j. If there is a ring, j will surely catch up with I;

3. If j is not empty and I and j are equal, this linked list is a ring.

 

1 # include <stdio. h> 2 # include <stdlib. h> 3 # include <string. h> 4 typedef struct student // define the chain table structure 5 {6 int num; 7 struct student * pnext; 8} stu, * pstu; 9 void link_tail_insert (pstu * phead, pstu * ptail, int I); 10 void link_show (pstu); 11 void link_judge_loop (pstu phead); 12 void main () {13 pstu phead, ptail; 14 int I; 15 phead = NULL; 16 ptail = NULL; 17 while (scanf ("% d", & I )! = EOF) {18 link_tail_insert (& phead, & ptail, I); 19} 20 link_show (phead); 21 ptail-> pnext = phead; // create a single-chain table with 22 link_judge_loop (phead); 23 system ("pause"); 24 25} 26 void link_tail_insert (pstu * phead, pstu * ptail, int I) {// create a chain table 27 pstu pnew; 28 pnew = (pstu) malloc (sizeof (stu); 29 memset (pnew, 0, sizeof (stu )); 30 pnew-> num = I; 31 if (* ptail = NULL) {32 * phead = pnew; 33 * ptail = pnew; 34} 35 else {36 (* ptail)-> pnext = pnew; 37 * ptail = pnew; 38} 39} 40 void link_show (pstu phead) {// output chain table 41 pstu pshow; 42 pshow = phead; 43 if (phead = NULL) 44 {45 printf ("no exsit \ n"); 46 return; 47} 48 while (pshow! = NULL) {49 printf ("% d", pshow-> num); 50 pshow = pshow-> pnext; 51} 52 putchar ('\ n '); 53} 54 void link_judge_loop (pstu phead) {// determine whether there is a ring 55 pstu I, j; 56 I = j = phead; 57 while (j! = NULL) {58 I = I-> pnext; 59 j = j-> pnext; 60 if (j = NULL) // j should be taken step by step to determine whether it is NULL, if it is null, the end loop 61 break; 62 j = j-> pnext; 63 if (I = j) // I and j are equal, with a ring of 64 break; 65} 66 if (j! = NULL & I = j) 67 printf ("link has loop \ n"); 68 else 69 printf ("link has no loop \ n"); 70}

 

Related Article

Contact Us

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.