题目
将单链表的链接顺序反转过来
例:
输入:1→2→3→4→5
输出:5→4→3→2→1
迭代方式
public ListNode iterate(ListNode head){
ListNode prev = null;
ListNode next;
ListNode curr = head;
while(curr!=null){
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
递归方式
public ListNode recursion(ListNode node){
if(node == null || node.next == null){
return node;
}
ListNode newNode = recursion(node.next);
node.next.next = node;
node.next = null;
return newNode;
}