简体   繁体   English

双链表

[英]Doubly Linked List

I've been trying to figure out how to reverse the order of a doubly-linked list.I've recently made an account on hackerrank and this was my 10th problem. 我一直在试图弄清楚如何反转双向链接列表的顺序。我最近在hackerrank上建立了帐户,这是我的第十个问题。 It took me 1 hour to figure out the solution (I used pen and paper and tried many times) and finally it passed as correct. 我花了1个小时才弄清楚解决方案(我用笔和纸试了好多次),最后还是以正确的方式通过了。 After that, I saw some answers submitted my some other folks.Their code was very small in length in comparison to mine or you think my answer is also okay. 之后,我看到其他人提交了一些答案,与我的代码相比,他们的代码长度很小,或者您认为我的答案还可以。 I have no one to ask to so I came here... I feel dumb when I see that.Can I improve it in future?? 我没有人要问,所以我来到这里。 (forgive me if you think this is a dumb question) (如果您认为这是一个愚蠢的问题,请原谅我)

    Node Reverse(Node head) {
     Node prevNode = null;
     Node NextNode = null;
     Node m = head;
     Node upComingNode = null;
     Node temp = head;
     if(head == null){
      return head;
  }
    else{
        while(temp!=null){
            NextNode = temp.next;
            temp.next = prevNode;
            m.prev = upComingNode;
            prevNode = temp;
            upComingNode = prevNode.next;
            m = temp;
            temp = NextNode;  
        }
       head = prevNode;
    }
    return head;


}

I am not sure what language you are working in, but to reverse a doubly linked list you, in brief, you want to swap your next and prev nodes for each node. 我不确定您使用的是哪种语言,但是简单地说,要反转双向链表,您想为每个节点交换下一个和上一个节点。 This can be done fairly shortly and the pseudocode is below: 这可以很快完成,伪代码如下:

while(currNode != tail){
    currNode.nextNode = tempNode
    currNode.nextNode = currNode.prevNode
    currNode.prevNode = tempNode
    currNode = currNode.prevNode
}

Note that we set the next node to iterate on as the previous node, since the previous node is actually pointing to the next node now that we made the switch. 请注意,我们将下一个节点设置为作为上一个节点进行迭代,因为在进行切换后,上一个节点实际上指向下一个节点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM