mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-10 00:09:06 +01:00
cs: add «143. Reorder List»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
7dc90ebe06
commit
54e3ac8c5a
1 changed files with 38 additions and 0 deletions
38
cs/reorder-list.cs
Normal file
38
cs/reorder-list.cs
Normal file
|
@ -0,0 +1,38 @@
|
||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Definition for singly-linked list.
|
||||||
|
* public class ListNode {
|
||||||
|
* public int val;
|
||||||
|
* public ListNode next;
|
||||||
|
* public ListNode(int val=0, ListNode next=null) {
|
||||||
|
* this.val = val;
|
||||||
|
* this.next = next;
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
*/
|
||||||
|
public class Solution {
|
||||||
|
private List<ListNode> ListAsList(ListNode head) {
|
||||||
|
var result = new List<ListNode>();
|
||||||
|
|
||||||
|
for (var node = head; node != null; node = node.next) {
|
||||||
|
result.Add(node);
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void ReorderList(ListNode head) {
|
||||||
|
var nodes = ListAsList(head);
|
||||||
|
|
||||||
|
ListNode node = head;
|
||||||
|
for (int i = 1, j = nodes.Count - 1; i <= j; ++i, --j) {
|
||||||
|
node.next = nodes[j];
|
||||||
|
node = node.next;
|
||||||
|
|
||||||
|
node.next = nodes[i];
|
||||||
|
node = node.next;
|
||||||
|
}
|
||||||
|
node.next = null;
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue