Created
October 29, 2011 20:07
-
-
Save blaineh/1325016 to your computer and use it in GitHub Desktop.
Defined linked list --> Reversed
This file contains 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
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
namespace ConsoleApplication1 | |
//Class program is our naming convention. | |
//Capitalize classes and not functions. | |
//Node head is the start of the linked list. | |
//Next points to the next node in the list. | |
//insertIntoRear adds a node to the end of the linked list. | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
Node head = new Node("Likes"); | |
head = insertIntoFront(head, "Blaine"); | |
insertIntoRear(head, "Beer"); | |
printNodeList(head); | |
head = reverseNodeList(head); | |
Console.WriteLine(); | |
printNodeList(head); | |
Console.ReadKey(); | |
} | |
//void means it doesnt return anything. | |
//This is us setting up the linked list one function at a time. | |
static void printNodeList(Node head) | |
{ | |
Node temp = head; | |
while (temp != null) | |
{ | |
Console.WriteLine(temp.value); | |
temp = temp.next; | |
} | |
} | |
static Node insertIntoFront(Node head, string data) | |
{ | |
Node newNode = new Node(data); | |
newNode.next = head; | |
return newNode; | |
} | |
static void insertIntoRear(Node head, string data) | |
{ | |
Node newNode = new Node(data); | |
Node temp = head; | |
while (temp.next != null) | |
{ | |
temp = temp.next; | |
} | |
temp.next = newNode; | |
} | |
//This is our method for reversing the list. | |
//http://stackoverflow.com/questions/1116720/how-to-read-a-singly-linked-list-backwards | |
static Node reverseNodeList(Node head) | |
{ | |
Node prev = null; | |
Node current = head; | |
Node nextNode = null; | |
while (current != null) | |
{ | |
nextNode = current.next; | |
current.next = prev; | |
prev = current; | |
current = nextNode; | |
} | |
return prev; | |
} | |
class Node | |
{ | |
public Node(string data) | |
{ | |
value = data; | |
next = null; | |
} | |
public string value; | |
public Node next; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment