单向链表的反转是一个经典的算法题。
需求:
原链表中的数据为:head->①->②->③->④
反转后的链表需为:head->④->③->②->①
反转所需设计的API:
public void reverse() //对整个链表进行反转
public Node reverse(Node curr) // 反转链表中的某个结点,并返回反转后的curr结点
在反转的过程中,需要使用递归完成反转。
即:从原链表的第一个结点(不包括头结点)开始,依次递归调用反转当前结点,直到把最后一个结点反转结束。
反转流程:
原链表中的数据为:head->①->②->③->④
第一次: head->④ 未反转:①->②->③
第二次: head->④->③ 未反转:①->②
第三次: head->④->③->② 未反转:①
第四次: head->④->③->②->① 未反转:
即①要完成反转,需要②③④完成反转
②要完成反转,需要③④完成反转
③要完成反转,需要④完成反转
④要完成反转,需要判断它是最后一个结点
首先来构建reverse()函数:
① 若当前链表为空,则不做任何操作
② 若不为空,则递归调用reverse(Node curr)函数。
public void reverse(){
if (isEmpty()){
return;
}
reverse(head.next);
}
再来构建reverse(Node curr)函数:
① 若当前要反转的结点为最后一个结点,则将头结点指向该结点
② 若不是则递归调用revrse(curr.next)
public Node reverse(Node curr) {
if (curr.next==null){
head.next = curr;
return curr;
}
Node pre = reverse(curr.next);
pre.next = curr;
curr.next = null;
return curr;
}
此例子中:
④是最后的结点
因此curr(③结点)在调用reverse(curr.next)时,curr.next为④结点。返回的pre则是④结点,④结点在反转后作为③的前一个结点,因此pre.next指向curr(③结点),同时返回③结点作为②结点的前一个结点(pre)。
附上单向链表的java实现:
public class LinkList<T> implements Iterable<T>{
private Node head;
private int N;
private class Node{
T item;
Node next;
private Node(T item, Node next){
this.item = item;
this.next = next;
}
}
public LinkList(){
this.head = new Node(null,null);
this.N = 0;
}
public void clear(){
head.next = null;
N = 0;
}
public int length(){
return N;
}
public Boolean isEmpty(){
return N==0;
}
public T get(int i){
Node n = head.next;
for (int index = 0; index < i;index++){
n = n.next;
}
return n.item;
}
public void insert(T t){
Node n = head;
for (int index = 0; n.next != null; index++) {
n = n.next;
}
Node newNode = new Node(t,null);
n.next = newNode;
N++;
}
public void insert(int i, T t) {
Node pre = head;
for (int index = 0; index <= i-1;index++){
pre = pre.next;
}
Node nextNode = pre.next;
Node n = new Node(t,nextNode);
pre.next = n;
N++;
}
public T remove(int i){
Node pre = head;
for (int index = 0; index < i-1; index++){
pre = pre.next;
}
Node curr = pre.next;
Node nextNode = curr.next;
pre.next = nextNode;
N--;
return curr.item;
}
public int indexOf(T t){
Node n = head;
for (int i = 0; n.next != null;i++){
n = n.next;
if (n.item.equals(t)){
return i;
}
}
return -1;
}
public void reverse(){
if (isEmpty()){
return;
}
reverse(head.next);
}
public Node reverse(Node curr) {
if (curr.next==null){
head.next = curr;
return curr;
}
Node pre = reverse(curr.next);
pre.next = curr;
curr.next = null;
return curr;
}
@Override
public Iterator<T> iterator() {
return new LIterator();
}
private class LIterator implements java.util.Iterator{
private LinkList.Node n;
public LIterator() {
this.n = head;
}
@Override
public boolean hasNext() {
return n.next!=null;
}
@Override
public Object next() {
n = n.next;
return n.item;
}
}
}