单向链表的反转JAVA实现(咋个办呢 zgbn)
相关文章:单向连表的反转JAVA实现(循环)(咋个办呢 zgbn)
分析
JAVA代码实现一个单向连表的反转处理。
图1
主要想实现思想,直接改变链表节点的指针方向。
图2
从图1
分析,链表的最后一个节点的指向地址为NULL,那么设想一下只需要从后向前依次的反转节点指向地址到前一个节点,就得到了图2
的结果。
实现
程序代码实现方面,可以使用递归算法,递归的1个特点层级进入递归时可以实现对链表的“从先到后”的遍历访问,这样方便程序定位到链表的最后一个节点;递归的2个特点是当程序退出递归时,正好是一种倒序的对链表的访问过程,只需要在这个过程进行指向地址反转即可。
代码
1、单向连表的节点类
public class Item {
private int value;
private Item next;
public Item(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public Item setValue(int value) {
this.value = value;
return this;
}
public Item getNext() {
return next;
}
public Item setNext(Item next) {
this.next = next;
return this;
}
@Override
public String toString() {
return String.valueOf(this.value);
}
}
2、单向连表类
class ItemList {
/**
* 起始节点对象
*/
private Item item;
/**
* 最后节点对象
*/
private Item endItem;
/**
* 构造函数,构建链表实体
* @param values 链表存储数字
*/
public ItemList(int... values) {
int len = values.length;
Item item = null;
for (int i = 0; i < len; i++) {
if (i == 0) {
item = this.item = this.endItem = new Item(values[i]);
} else {
item = this.endItem = item.setNext(new Item(values[i])).getNext();
}
}
}
@Override
public String toString() {
StringBuffer str = new StringBuffer();
Item item = this.item;
if (item != null) {
str.append(item.getValue()).append(",");
while (item.getNext() != null) {
item = item.getNext();
str.append(item.getValue()).append(",");
}
}
return str.toString();
}
/**
* 执行链表反转动作
*/
public void inversion() {
if (this.item != null && this.item.getNext() != null) {
this.inversion(this.item, this.item.getNext());
Item tm = this.endItem ;
this.endItem = this.item ;
this.item = tm ;
}
}
/**
* 链表反转递归实现
* @param thisItem 当前节点
* @param nextItem 当前节点的下一个节点
* @return 当前节点
*/
private Item inversion(Item thisItem, Item nextItem) {
if (nextItem.getNext() != null) {
nextItem = inversion(nextItem, nextItem.getNext());
}
nextItem.setNext(thisItem.setNext(null));
return thisItem;
}
}
3、执行和结果
public class LinkedListInversionDemo {
private static ItemList ilist = new ItemList(1, 2, 3, 4, 5, 6, 7, 8, 9);
public static void main(String[] args) {
System.out.println(String.format("单向链表数据:\t%s", ilist));
ilist.inversion();//执行反转动作
System.out.println(String.format("单向链表反转后的数据:\t%s", ilist));
}
}