Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

my first commit #17

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
# Data Structures and Algorithms in C

## Won't count towards prize
# Won't count towards prize
# May use of C and C++ language

68 changes: 68 additions & 0 deletions link list
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
// Simple C++ program to find n'th node from end
#include <bits/stdc++.h>
using namespace std;

/* Link list node */
struct Node {
int data;
struct Node* next;
};

/* Function to get the nth node from the last of a linked list*/
void printNthFromLast(struct Node* head, int n)
{
int len = 0, i;
struct Node* temp = head;

// count the number of nodes in Linked List
while (temp != NULL) {
temp = temp->next;
len++;
}

// check if value of n is not
// more than length of the linked list
if (len < n)
return;

temp = head;

// get the (len-n+1)th node from the beginning
for (i = 1; i < len - n + 1; i++)
temp = temp->next;

cout << temp->data;

return;
}

void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node = new Node();

/* put in the data */
new_node->data = new_data;

/* link the old list off the new node */
new_node->next = (*head_ref);

/* move the head to point to the new node */
(*head_ref) = new_node;
}

// Driver Code
int main()
{
/* Start with the empty list */
struct Node* head = NULL;

// create linked 35->15->4->20
push(&head, 20);
push(&head, 4);
push(&head, 15);
push(&head, 35);

printNthFromLast(head, 4);
return 0;
}