LeetCode206-逆转链表-简单-Java实现

搞混了头结点和第一个节点,要仔细读题哦~

/**
 * 用头插法 反转链表
 * 注意这里不要管头结点
 * @param head
 * @return
 */
public ListNode reverseList (ListNode head) {
	if (head == null || head.next == null) return head;
	ListNode node = null;  // 反转后新链表
	
	/*
	 * 创建一个临时节点,存储原链表现在的节点
	 * 修改当前节点指针域,当前节点指向反转后的链表
	 * 更新反转后的链表
	 * 原链表指向下一个节点
	 */
	while (head != null) {	
		ListNode next = head.next;  //  备份原链表下一个节点
		
		head.next = node;  //  cur 指向 node
		node = head;  //  node永远都是第一个节点
		head = next;  //  原链表 cur指向下一个节点
	}
	return node;
}

原来错误的代码:
为什么测试不通过啊

	public ListNode reverseList (ListNode head) {
	if (head == null || head.next == null) return null;
	ListNode cur = head.next;   //  就是这里错了!!
	ListNode node = null;  // 反转后新链表
	
	while (cur != null) {	
		ListNode next = cur.next;  //  备份原链表下一个节点
		
		cur.next = node;  //  cur 指向 node
		node = cur;  //  node永远都是第一个节点
		cur = next;  //  原链表 cur指向下一个节点
	}
	head.next = node; // 将原链表的头结点指向反转后的链表
	return node;
}

测试用例显示:
在这里插入图片描述
考虑头结点的话:

	/**
	 * 用头插法 反转链表
	 * 新链表的头结点
	 * 这个链表类中,不能有参数,因为测试类中是直接生成表的不是节点
	 * @param head
	 * @return
	 */
	public Node<E> reverseList () {
		if (head == null || head.next == null) return null;
		Node<E> cur = head.next;   //  原链表  cur指向第一个节点
		Node<E> node = null;  // 反转后新链表
		/*
		 * 创建一个临时节点,存储原链表现在的节点
		 * 修改当前节点指针域,当前节点指向反转后的链表
		 * 更新反转后的链表
		 * 原链表指向下一个节点
		 */
		while (cur != null) {	
			Node<E> next = cur.next;  //  备份原链表下一个节点
			
			cur.next = node;  //  cur 指向 node
			node = cur;  //  node永远都是第一个节点
			cur = next;  //  原链表 cur指向下一个节点
		}
		head.next = node; // 将原链表的头结点指向反转后的链表
		return node;
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值