您当前的位置: 首页 >  leetcode

white camel

暂无认证

  • 3浏览

    0关注

    442博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

leetcode——206.反转链表

white camel 发布时间:2020-10-27 19:32:43 ,浏览量:3

Leetcode链表相关题目
  • 206.反转链表

在这里插入图片描述

1、递归方法

如下图, 假如我们写的reverseList(head)方法的功能就是反转成功的结果; 在这里插入图片描述 reverseList(head.next)时如下图 在这里插入图片描述 在这里插入图片描述

如果reverseList(head.next)此时就已经反转了 1 -> 2 -> 3 -> 4 -> null, 如果要想成功反转为1 2 3 4 5 null, 我们只需要解决4.next -> 5, 5.next -> null, 这样就完成了反转

public class ListNode{
	int val;
	ListNode next;
	ListNode(int x) {
		val = x;
	}
}

class Solution {
	public ListNode reverseNode(ListNode head) {
		
		//if (head == null) return null;	  // 等同 return head
		//if (head.next == null) return head; // 此时就一个节点
		if (head == null || head.next == null)
			return head;
		
		// 此时的newNode就是节点4, 1 -> 2 -> 3 -> 4 -> null
		ListNode newNode = reverseNode(head.next) 
		// 此时要想办法将4的next指向5; 因为此时head指向5, head.next就指向4, head.next.next指向head即可
		// 也就是4.next指向5
		head.next.next = head;
		head.next = null;
		
		return newNode;
	}
}

这样就完成了递归反转链表;

2、迭代的方式

在这里插入图片描述

  • 因为题目中只提供了一个head指针, 所以我要想达到反转的效果, 就只能从head着手;
  • 首先提供一个newHead, 指向null, 我们期待的结果是最后返回的这个newHead指向1 -> 2 -> 3 -> 4 -> 5 -> null

在这里插入图片描述 在这里插入图片描述

思路 : 先让head指向newHead, 然后newHead指向head, 然后head指向它之前的next

一开始就要使用一个变量tmp来引用这head.next, 不然后面的节点都释放了 在这里插入图片描述 在这里插入图片描述 在这里插入图片描述

public class ListNode{
	int val;
	ListNode next;
	ListNode(int x) {
		val = x;
	}
}

class Solution {
	public ListNode reverseNode(ListNode head) {
	
		if (head == null || head.next == null) return head;
		
		ListNode newHead = null;
		while (head != null) {
			ListNode tmp = head.next; // tmp先指向head.next
			head.next = newHead;
			newHead = head;
			head = tmp;
		}
		return newNode;
	}
}

在这里插入图片描述

在这里插入图片描述 在这里插入图片描述 在这里插入图片描述 终止条件为head != null

关注
打赏
1661428283
查看更多评论
立即登录/注册

微信扫码登录

0.0406s