剑指 Offer 24. 反转链表
题目:
思路:
1.用temp存放head.next,再变换指针
2.递归(想不出来,后面继续看看)
题解:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre = null;
while (head != null) {
// 自己当时一直想把temp放外面,一直写不出来————先实现功能,再进行优化
ListNode temp = head.next;
head.next = pre;
pre = head;
head = temp;
}
return pre;
}
}