public class ReverNode {
class Node{
int val;
Node next;
}
//非递归
public static Node reverseUnRecur(Node head){
if(head==null || head.next==null){
return head;
}
Node pre = null;
Node next = null;
Node cur = head;
while(cur !=null){
//记住当前节点的next
next = cur.next;
//当前节点指向前一个节点
cur.next = pre;
//让pre记住当前节点
pre = cur;
//当前节点后移
cur = next;
}
return pre;
}
//递归
public static Node reverseRecur(Node head){
if(head==null || head.next==null){
return head;
}
Node next = head.next;
head.next = null;
Node revNode = reverseRecur(next);
next.next = head;
return revNode;
}
}
class Node{
int val;
Node next;
}
//非递归
public static Node reverseUnRecur(Node head){
if(head==null || head.next==null){
return head;
}
Node pre = null;
Node next = null;
Node cur = head;
while(cur !=null){
//记住当前节点的next
next = cur.next;
//当前节点指向前一个节点
cur.next = pre;
//让pre记住当前节点
pre = cur;
//当前节点后移
cur = next;
}
return pre;
}
//递归
public static Node reverseRecur(Node head){
if(head==null || head.next==null){
return head;
}
Node next = head.next;
head.next = null;
Node revNode = reverseRecur(next);
next.next = head;
return revNode;
}
}