java leetcode链表翻转
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
迭代翻转:
思路---> 1->2->3->4->5->null =>5->4->3->2->1->null
1->null ==>2->1->null=>3->2->1->null ..........
public ListNode reverseList(ListNode head) {
ListNode now;
ListNode node = null;
while(head != null){
now = head; //now = 1 ->2->3....
head = head.next; //1->2....... = 2->3.....
now.next = node; //now = 1->null
node = now; //node = 1->null
}
return node;
}
递归翻转:
思路---> 1->2->3->4->5->null =>5->4->3->2->1->null
先找到出口。 5->null => 4->5->4 => 5->4->null .....................
public ListNode reverseList(ListNode head) {
if(head.next != null || head != null){
return head;
}
ListNode newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
这里有点难理解,下面是自己画的逻辑图