题目
反转一个单链表。
思路
1 两种方案,递归和非递归
2 这里用到了链表的数据结构,注意数据结构的定义,包括构造函数等
3 递归方案 递归函数传递两个参数,开始是头结点和null
1 先判断head是否为空节点,空直接返回null
2 next 保存 head 的下个结点, head指向为空
3 此时 next 和head 的角色就是一开始head 和null的角色
非递归 关于非递归的方案通常都是用while循环来解决,while的循环条件是head不能为空
其余类似递归方案, next存下一个head, head指向newhead, head 和newhead 角色对调为next , head
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
return ListNodeInt(head, null);
// ListNode newHead = null;
// while (head != null){
// ListNode next = head.next;
// head.next = newHead;
// newHead = head;
// head = next;
// }
// return newHead;
}
public ListNode ListNodeInt(ListNode head, ListNode newHead){
if(head == null)
return newHead;
ListNode next = head.next;
head.next = newHead;
return ListNodeInt(next, head);
}
}