题目
地址:https://leetcode-cn.com/problems/reverse-linked-list/
难度:简单
描述
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
实例:
问题分析
这道算法题,说直白点就是:如何让后一个节点指向前一个节点!在下面的代码中定义了一个 next 节点,该节点主要是保存要反转到头的那个节点,防止链表 “断裂”。
题解
解法-迭代
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}* ListNode(int val) { this.val = val; }* ListNode(int val, ListNode next) { this.val = val; this.next = next; }* }*/class Solution {public ListNode reverseList(ListNode head) {ListNode pre =null, next;while (head != null){//存储下一个节点的指针,否则修改完节点指针就找不到下一个节点了next = head.next;//指针修改:把前置节点赋值给当前节点的nexthead.next = pre;//把处理完的节点存到pre节点上pre = head;//处理下一个节点head = next;}return pre;}}
解法-递归
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}* ListNode(int val) { this.val = val; }* ListNode(int val, ListNode next) { this.val = val; this.next = next; }* }*/class Solution {public ListNode reverseList(ListNode head) {if ( head == null || head.next == null){return head;}ListNode newNode = reverseList(head.next);head.next.next =head;head.next = null;return newNode;}}
