103-算法应用【字符串反转】代码实现

字符串反转


本文链接:https://www.cnblogs.com/cheng2839

介绍

将字符串倒序组织

分析

我们都知道StringBuilder类有个reverse()方法,可以将字符串反转,但这里考察的是算法实现。

所以我们采取链表存储字符串,然后将链表反转。

实现

下面是用java实现算法:


//本文链接https://www.cnblogs.com/cheng2839
public
class $Convert { //反转方法 public static Entry convert(Entry root) { if (root == null) return null; Entry i = root, j = root.next; i.next = null; while (j != null) { Entry head = j.next; j.next = i; i = j; j = head; } return i; } //依次打印字符串 public static void print(String s, Entry n) { System.out.println(s); while (n != null) { System.out.print(n.value + ", "); n = n.next; } System.out.println(); } public static void main(String[] args) { String s = "https://www.cnblogs.com/cheng2839"; Entry root = new Entry("", null); Entry head = root; for (char c : s.toCharArray()) { head.next = new Entry(c, null); head = head.next; } head = root.next; print("原始字符串是:", head); Entry result = convert(head); print("反转后的字符串是:", result); } } //实体类 class Entry { Object value; Entry next; public Entry(Object value, Entry next) { this.value = value; this.next = next; } }
____________________________特此,勉励____________________________
本文作者cheng2839
本文链接https://www.cnblogs.com/cheng2839
关于博主:评论和私信会在第一时间回复。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角【推荐】一下。您的鼓励是博主的最大动力!
原文地址:https://www.cnblogs.com/cheng2839/p/14593682.html