交换单链列表的最后两个节点

编程入门 行业动态 更新时间:2024-10-11 07:25:05
本文介绍了交换单链列表的最后两个节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何交换链表的最后两个节点?我正在尝试使用一个辅助节点,因为我认为有必要避免在此过程中丢失"一个节点...

How can I swap the last two nodes of a linked list? I'm trying to use a helper node as I think it's needed to avoid 'losing' a node in the process...

... Node node3 = new Node("Hi", null) ; Node node4 = new Node("Hello", null) ; ... // swap node3 & node4 Node temp = node3.succ ; node3.succ = null ; // this should be the last node now, so i set its pointer to null node2.succ = temp ; // the second's node successor becomes what used to be the last node temp = node4 ; // not sure how to use temp here. what should it point to if at anything?

我认为我做错了,有什么提示吗?

I think I'm doing this wrong, any hints?

推荐答案

假设您有一个链表 A->B->C ,并且您想交换 B 和 C :

Suppose you have a linked list A -> B -> C, and you want to swap B and C:

  • 设置T * = B(将B存储在某个地方)
  • 设置A.next = C
  • 设置T * .next = C.next(这可以从仅在列表末尾进行操作而得到概括)
  • 设置C.next = T *
  • 更多推荐

    交换单链列表的最后两个节点

    本文发布于:2023-11-29 02:41:40,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1644966.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:节点   两个   列表

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!