链表是一种添加和删除快,查询慢的数据结构,因此链表如果要实现倒叙没有数组那么便捷,对于链表的倒叙,采取的方法是逐步后移,逐步反向的方法。话不多说,先呈上代码:
public static listNode listReverse(listNode head){
listNode pre=null;
listNode next;
while (head!=null){
next=head.next;
head.next=pre;
pre=head;
head=next;
}
return pre;
}
首先定义两个listNode,pre和next,将head.next赋给next,然后将head.next置空,将pre指向head,然后head后移,这一轮循环之后,每个指针都后移了一位,并且将head.next指向了pre,链表的方向反转了,接下来一轮的循环中,下一个节点会实现反转,依次循环下去,最终链表结构将会实现反转。