【LeetCode】206.反转链表

本文详细解析了单链表反转的算法实现,包括迭代和递归两种方法,并提供了Eclipse环境下可运行的完整代码示例。通过对算法的深入探讨,对比了不同方法的性能表现,旨在帮助读者理解链表操作的核心技巧。

1.题目描述

反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

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) {
        if(head == null || head.next == null){
			return head;
		}
		ListNode pos = null;
		ListNode lastNode = null;
		lastNode = head;
		pos = head.next;
		head.next = null;
		head = pos;		
		while(head.next != null){
			pos = head.next;
			head.next = lastNode;
			lastNode = head;
			head = pos;
		}
		head.next = lastNode;
		return head;
    }
}

2.1 eclipse 完整可调试代码:

package single_100;

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
/**
 * TODO :  创建一个 链表,翻转链表
 * @author Infosec_jy
 *
 */
public class ReverseList_206 {
	public static void main(String[] args) {
		int[] vals = new int[]{1,2,3,4,5};
		ListNode head = new ListNode(vals[0]);
		ListNode pos = head;
		for(int i = 1;i < vals.length; i++){
			pos.next = new ListNode(vals[i]);
			pos = pos.next;
		}
	//	ListNode head = null;			      考虑 head 为 null
	//	ListNode head = new ListNode(6);  考虑 head.next 为 null
		ListNode result = reverseList(head);
		while(head.next != null){
			System.out.print(head.val);
			head = head.next;
		}
		System.out.print(head.val);
	}
	public static ListNode reverseList(ListNode head) {
		if(head == null || head.next == null){
			return head;
		}
		ListNode pos = null;
		ListNode lastNode = null;
		lastNode = head;
		pos = head.next;
		head.next = null;
		head = pos;		
		while(head.next != null){
			pos = head.next;
			head.next = lastNode;
			lastNode = head;
			head = pos;
		}
		head.next = lastNode;
		return head;
    }
}




3. 性能评级:

 

4. 思考过程:

   第一次  有考虑 存储到 stringBuffer中,再转为 int[] 数组,实现。感觉会比较消耗空间,想法作废。

   现在用 递归 做,感觉 不复杂,为什么 性能差这么多呢。  要考虑。

 

5. 后期优化:

 大神的解法:

public static ListNode reverseList(ListNode head) {
		
		ListNode pre = null;
		ListNode cur = head;
		ListNode next;
		while(cur != null){
			next = cur.next;
			cur.next = pre;
			pre = cur;
			cur = next;
		}
		return pre;
	}

性能:

 

思考:  尽量不定义多余变量,尽量定义 局部变量。争取每个变量 都有其特殊且简单的意义。

 

 

### 反转单向链表的算法实现 反转单向链表是一个经典的算法问题,在 LeetCode 的第 206 题中有详细的描述。以下是该问题的核心思路和两种常见的实现方法。 #### 思路分析 要反转一个单向链表,可以通过迭代或者递归来完成。无论是哪种方式,其核心目标都是改变每个节点的 `next` 指针方向,使得原本指向下一个节点的方向改为指向前一个节点[^1]。 --- #### 方法一:迭代法 迭代法是一种直观且高效的解决方案。通过维护三个指针变量——前驱节点 (`prev`)、当前节点 (`curr`) 和临时存储下一节点的变量 (`temp`),逐步更新链表中的指针关系。 ##### 实现代码 ```python class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def reverseList(head: ListNode) -> ListNode: prev = None # 初始化前驱节点为空 curr = head # 当前节点从头节点开始 while curr is not None: # 循环直到当前节点为空 temp = curr.next # 保存当前节点的下一个节点 curr.next = prev # 修改当前节点的 next 指向前驱节点 prev = curr # 更新前驱节点为当前节点 curr = temp # 移动到下一个节点 return prev # 返回新的头节点(原链表的尾节点) ``` 这种方法的时间复杂度为 O(n),其中 n 是链表的长度;空间复杂度为 O(1)。 --- #### 方法二:递归法 递归法虽然逻辑上稍显复杂,但它提供了一种优雅的方式来解决问题。递归的关键在于定义好终止条件以及如何处理每一层递归返回的结果。 ##### 实现代码 ```cpp // C++ 版本 ListNode* reverseList(ListNode* head) { if (head == nullptr || head->next == nullptr) { // 终止条件:到达链表末尾 return head; } ListNode* newHead = reverseList(head->next); // 递归调用,获取新链表的头部 head->next->next = head; // 改变当前节点与其后续节点之间的连接 head->next = nullptr; // 清空当前节点的 next 指针 return newHead; // 返回新链表的头部 } ``` 递归方法同样具有时间复杂度 O(n),但由于需要额外的栈空间来支持函数调用,因此空间复杂度为 O(n)[^3]。 --- ### 对比与总结 - **迭代法** 更加高效,适合大规模数据场景下的应用。 - **递归法** 虽然简洁易懂,但在极端情况下可能会因为栈溢出而导致程序崩溃。 对于初学者来说,建议先掌握迭代法再尝试理解递归法。如果希望进一步学习链表操作的相关技巧,可以参考《王道数据结构考研复习指导》或其他经典教材[^2]。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值