Finding the middle of a linked list:
1: int findMiddle(node* head) {
2: node* middle = head; // the middle will be here
3: while (head != 0 && head->next != 0) {
4: head = head->next->next; // advance the head by two positions forward
5: middle = middle->next; // advance the middle by only one position
6: }
7: return middle->data;
8: }
Finding if a linked list has loops (uses almost the same code):
1: bool hasLoops(node* head) {
2: node* slowPtr = head; //we'll move slower into the list using this pointer
3: while (head != 0 && head->next != 0) {
4: head = head->next->next; // advance the head by two positions forward
5: slowPtr = slowPtr->next; // advance the slowPtr by only one position
6: if (head == slowPtr) //these can never become equal unless one pointer loops
7: return true; //back to a previous position, which means there's a loop
8: }
9: return false;
10: }
No comments:
Post a Comment