题目
题目链接
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
限制:
0 <= 节点个数 <= 5000
解题思路1
利用栈的先进后出性质。
代码
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null) {
return null;
}
Stack<ListNode> stack = new Stack<>();
ListNode temp = head;
while (temp != null) {
stack.push(new ListNode(temp.val));
temp = temp.next;
}
ListNode root = new ListNode(0);
ListNode l = root;
while (!stack.isEmpty()) {
l.next = stack.pop();
l = l.next;
}
return root.next;
}
}
解题思路2
递归法
递归终止条件 head=null或者 head.next=null
例如:1,2,3,4,5
理解上来说就是从头结点1递归到5 过程如下:1-》2-》3-》4-》5 再递归满足终止条件停止。当前结点就是翻转链表的头结点。
然后让它指向4就可以了呗。于是乎head.next.next = head 5.next=4
1-》2-》3-》4《-5
然后我们进行接下来的同样操作,但是需要注意,4和5的关系需要断开head.next=null 防止循环指向。
代码
class Solution {
public ListNode reverseList(ListNode head) {
//递归终止条件
if (head == null || head.next == null) return head;
//递归
ListNode root = reverseList(head.next);
//反向指向
head.next.next = head;
//防止循环指向
head.next = null;
return root;
}
}