Reversing single linked list in C#

后端 未结 13 662
说谎
说谎 2020-12-07 17:02

I am trying to reverse a linked list. This is the code I have come up with:

 public static void Reverse(ref Node root)
 {
      Node tmp = root;
      Node n         


        
相关标签:
13条回答
  • 2020-12-07 17:44

    That question gets asked a lot. When I was asked it in my interviews many years ago, I reasoned as follows: a singly-linked list is essentially a stack. Reversing a linked list is therefore a trivial operation on stacks:

    newList = emptyList;
    while(!oldList.IsEmpty())
        newList.Push(oldList.Pop());
    

    Now all you have to do is implement IsEmpty and Push and Pop, which are one or two lines tops.

    I wrote that out in about twenty seconds and the interviewer seemed somewhat perplexed at that point. I think he was expecting me to take about twenty minutes to do about twenty seconds work, which has always seemed odd to me.

    0 讨论(0)
提交回复
热议问题