[LeetCode]: 206: Reverse Linked List
题目:
Reverse a singly linked list.
思路1:直接用循环遍历即可
代码:
public static ListNode reverseList(ListNode head) { if(head == null || head.next == null){ return head; } ListNode nodeCurrent = head.next; ListNode nodeLast= head; head.next = null; while(nodeCurrent != null){ ListNode tempNode = nodeCurrent.next; nodeCurrent.next = nodeLast; nodeLast = nodeCurrent; nodeCurrent = tempNode; } return nodeLast; }
思路2:递归
public static ListNode reverseList(ListNode head) { if(head == null || head.next == null){ return head; } ListNode nodeCurrent = head.next; ListNode nodeNext = reverseList(nodeCurrent); head.next = null; nodeCurrent.next = head; return nodeNext; }