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; } }

 

posted @ 2021-03-29 18:27  温柔的星空,让你感动  阅读(99)  评论(0编辑  收藏  举报