交换单链列表的最后两个节点 [英] swap last two nodes of singly-linked list

查看:42
本文介绍了交换单链列表的最后两个节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

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

这篇关于交换单链列表的最后两个节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆