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

Create ReverseLinkList #166

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
82 changes: 82 additions & 0 deletions DataStructures/Lists/ReverseLinkList
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
// C# program for reversing the linked list
using System;

class GFG {

// Driver Code
static void Main(string[] args)
{
LinkedList list = new LinkedList();
list.AddNode(new LinkedList.Node(85));
list.AddNode(new LinkedList.Node(15));
list.AddNode(new LinkedList.Node(4));
list.AddNode(new LinkedList.Node(20));

// List before reversal
Console.WriteLine("Given linked list:");
list.PrintList();

// Reverse the list
list.ReverseList();

// List after reversal
Console.WriteLine("Reversed linked list:");
list.PrintList();
}
}

class LinkedList {
Node head;

public class Node {
public int data;
public Node next;

public Node(int d)
{
data = d;
next = null;
}
}

// function to add a new node at
// the end of the list
public void AddNode(Node node)
{
if (head == null)
head = node;
else {
Node temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = node;
}
}

// function to reverse the list
public void ReverseList()
{
Node prev = null, current = head, next = null;
while (current != null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
head = prev;
}

// function to print the list data
public void PrintList()
{
Node current = head;
while (current != null) {
Console.Write(current.data + " ");
current = current.next;
}
Console.WriteLine();
}
}

// This code is contributed by Mayank Sharma