单链表
/**
* 单链表
*/
public static class Linked {
private String value;
private Linked next;
public Linked(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Linked getNext() {
return next;
}
public void setNext(Linked next) {
this.next = next;
}
}
递归实现
/**
* 链表翻转,递归实现
*
* @param head head
* @return
*/
public Linked flipByRecursion(Linked head) {
if (head == null || head.next == null) return head;
Linked tailLinked = flipByRecursion(head.next);
head.next.setNext(head);
head.setNext(null);
return tailLinked;
}
循环实现
/**
* 循环实现
*
* @param head head
* @return
*/
public Linked flipByLoop(Linked head) {
if (head == null || head.next == null) return head;
Linked next = null;
Linked pre = null;
while (head != null) {
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
网友评论