Skip to content

Instantly share code, notes, and snippets.

@dgodfrey206
Last active May 19, 2019 18:35
Show Gist options
  • Save dgodfrey206/1506617d7c5c3484c698d412b9c15adc to your computer and use it in GitHub Desktop.
Save dgodfrey206/1506617d7c5c3484c698d412b9c15adc to your computer and use it in GitHub Desktop.
Counts the number of nodes in a circular linked list
#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;
}
@dgodfrey206
Copy link
Author

Create a smaller linked list by removing a node and counting the number of elements in that list.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment