反转链表(java实现)
2019-03-02 本文已影响0人
清泥洼
链表反转
节点数据结构如下:
class Node {
private Stringname;
private Nodenext;
public Node(String name) {
this.name = name;
}
链表反转的两种方式:递归和非递归
递归方式如下:
public NoderecursiveReverse(Node head) {
if (head ==null || head.next ==null) {
return head;
}
Node node = recursiveReverse(head.next);
head.next.next = head;
head.next =null;
return node;
}
非递归方式如下:
public Nodereverse(Node head) {
if (head ==null) {
return null;
}
Node pre = head;
Node node = pre.next;
pre.next =null;
while (node !=null) {
Node nodeNext = node.next;
node.next = pre;
pre = node;
node = nodeNext;
}
return pre;
}