面试题【从尾到头打印链表】精妙解法 面试题【002字符串替换空格】精妙解法 面试题【001二维数组中的查找】精妙解法

题目描述

输入一个链表,按链表值从尾到头的顺序返回一个List。html

解题思路

输入一个链表,从尾到头输出,正常的遍历都是从头至尾输出,而这里须要从尾到头输出,那么就是“先进后出”,也就是栈的功能。node

代码实现

栈的方式实现面试

public static List<int> PrintForStack(ListNode nodes)
{
    Stack<ListNode> listNodes = new Stack<ListNode>();
    ListNode node = nodes;
    while (node != null)
    {
        listNodes.Push(node);
        node = node.next;
    }

    List<int> list = new List<int>();
    foreach (var item in listNodes) {
        list.Add(item.item);
    }
    return list;
}

递归的方式实现数组

public static List<int> PrintForRecursion(ListNode node) {
    List<int> listNodes = new List<int>();
    PrintForRecursion(node, listNodes);
    return listNodes;
}

private static void PrintForRecursion(ListNode node, List<int> list)
{
    if (node != null) {
        if (node.next != null) {
            PrintForRecursion(node.next, list);
        }
        list.Add(node.item);
    }
}

想入非非:扩展思惟,发挥想象

1.输入一个链表,返回一个倒过来的链表ide

public static ListNode PrintForReverse(ListNode nodes)
{
    Stack<ListNode> listNodes = new Stack<ListNode>();
    ListNode node = nodes;
    while (node != null)
    {
        listNodes.Push(node);
        node = node.next;
    }

    ListNode reverseNode = listNodes.Pop();
    var temp = reverseNode;
    foreach (var item in listNodes)
    {
        item.next = null;
        temp.next = item;
        temp = item;
    }
    return reverseNode;
}

2.生成一个链表post

public static ListNode CreateNodeList(int length)
{
    ListNode listNode = new ListNode(0);
    var temp = listNode;
    for (int i = 1; i < length; i++)
    {
        temp = nextList(temp, i);
    }

    return listNode;

    //下一个
    ListNode nextList(ListNode node, int value)
    {
        while (node.next != null)
        {
            node = node.next;
        }
        var next = new ListNode(value);
        node.next = next;
        return next;
    }
}

测试

[Fact]
public void TestList()
{
    ListNode listNode = Coding003.CreateNodeList(10);
    List<int> test = Coding003.PrintForStack(listNode);
    for (int i = 0; i < 10; i++)
    {
        Assert.Equal(i, test[9 - i]);
    }

    List<int> test2 = Coding003.PrintForRecursion(listNode);
    for (int i = 0; i < 10; i++)
    {
        Assert.Equal(i, test2[9 - i]);
    }
}

[Fact]
public void Test()
{
    ListNode listNode = Coding003.CreateNodeList(10);
    string o = JsonConvert.SerializeObject(listNode);

    List<int> test = Coding003.PrintForStack(listNode);
    string t = JsonConvert.SerializeObject(test);

    List<int> test2 = Coding003.PrintForRecursion(listNode);
    string t2 = JsonConvert.SerializeObject(test2);

    ListNode test3 = Coding003.PrintForReverse(Coding003.PrintForReverse(listNode));
    string t3 = JsonConvert.SerializeObject(test3);

    Assert.Equal(test, test2);
    Assert.Equal(o, t3);
}
View Code

面试题【002字符串替换空格】精妙解法测试

面试题【001二维数组中的查找】精妙解法url

相关文章
相关标签/搜索