Last active
May 19, 2019 18:35
-
-
Save dgodfrey206/1506617d7c5c3484c698d412b9c15adc to your computer and use it in GitHub Desktop.
Counts the number of nodes in a circular linked list
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
#include<string> | |
#include<map> | |
#include<vector> | |
using namespace std; | |
struct Node{ | |
int data; | |
Node*next=nullptr; | |
}; | |
void display(Node*head){ | |
if (!head) return; | |
Node* cur = head; | |
do { | |
cout<<cur->data<<" "; | |
cur = cur->next; | |
}while(cur != head); | |
cout<<endl; | |
} | |
Node* nn(int d){ | |
return new Node{d}; | |
} | |
int count(Node* head) { | |
if (!head) return 0; | |
if (head->next == head) return 1; | |
Node* rest = head->next; | |
head->next = head->next->next;; | |
int result = 1 + count(head->next); | |
head->next = rest; | |
return result; | |
} | |
/* | |
int count(Node* head) { | |
if (!head) return 0; | |
} | |
int count(Node* head) { | |
if (!head) return 0; | |
int result = 0; | |
Node* cur = head; | |
do { | |
result++; | |
cur = cur->next; | |
} while (cur != head); | |
return result; | |
} | |
*/ | |
Node* reverse(Node* head) { | |
if (!head || !head->next) return head; | |
Node* prev = head; | |
Node* cur = head->next; | |
do { | |
Node* nxt = cur->next; | |
cur->next = prev; | |
prev = cur; | |
cur = nxt; | |
} while (cur != head); | |
cur->next = prev; | |
return prev; | |
} | |
int main() { | |
auto h=nn(1); | |
h->next=nn(2); | |
h->next->next=nn(3); | |
h->next->next->next=nn(4); | |
h->next->next->next->next=h; | |
display(h); | |
cout<<count(h)<<endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Create a smaller linked list by removing a node and counting the number of elements in that list.