Created
November 1, 2021 08:47
-
-
Save dev-chee/0863eaa44b5280f6a81ba4d84553e701 to your computer and use it in GitHub Desktop.
revert a 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
| using System; | |
| namespace hello_csharp | |
| { | |
| class Program | |
| { | |
| class Node | |
| { | |
| public int val; | |
| public Node next; | |
| public Node(int val, Node next = null) | |
| { | |
| this.val = val; | |
| this.next = next; | |
| } | |
| } | |
| static void Main(string[] args) | |
| { | |
| // construct a list (1 -> 2 -> 3 -> 4 -> 5 -> NULL) | |
| var head = new Node(1); | |
| var prv = head; | |
| for (var i = 2; i <= 5; i++) | |
| { | |
| var node = new Node(i); | |
| prv.next = node; | |
| prv = node; | |
| } | |
| Print(head); | |
| // reverse the list (1 <- 2 <- 3 <- 4 <- 5 <- NULL) | |
| prv = null; | |
| var cur = head; | |
| while (cur != null) | |
| { | |
| var node = cur.next; | |
| cur.next = prv; | |
| prv = cur; | |
| cur = node; | |
| } | |
| head = prv; // new the head of list | |
| Print(head); | |
| } | |
| // print the list | |
| static void Print(Node head) | |
| { | |
| var cur = head; | |
| while (cur != null) | |
| { | |
| Console.Write($"{cur.val} "); | |
| cur = cur.next; | |
| } | |
| Console.WriteLine(); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment