206. 反转链表

反转一个单链表。

示例:

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

1、多画图理解会容易点。这个迭代法更简单些容易想。但是递归的更好理解,易读性略胜一筹。

2、递归,时间复杂度 O(n), 空间复杂度O(n)

迭代,时间复杂度 O(n), 空间复杂度O(1)

package com.data;

public class SolutionReverse {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		SolutionReverse plus = new SolutionReverse();
		ListNode l2 = new ListNode(5, new ListNode(6, new ListNode(4, new ListNode(5))));
		ListNode node = plus.reverseList(l2);
		while (node != null) {
			System.out.print(node.val + "--");
			node = node.next;
		}

		System.out.println();
		l2 = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5, new ListNode(6))))));
		node = plus.reverseList(l2);
		while (node != null) {
			System.out.print(node.val + "--");
			node = node.next;
		}

	}
	
	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;
	}

	public ListNode reverseList3(ListNode head) {
		ListNode parent = null;// 头结点他爹是空值
		ListNode son = head;// 头结点做起始节点当儿子遍历
		while (son != null) {
			ListNode sonson = son.next;// 儿子的儿子就是孙子
			son.next = parent;// 儿子指向他爹

			parent = son;// 儿子当爹
			son = sonson;// 孙子当儿子
		}
		return parent;// 反转后的头结点应该是son的爹
	}

	public ListNode reverseList2(ListNode head) {
		ListNode parent = head;
		ListNode son = head.next;
		head.next = null;
		while (son != null) {
			ListNode sonson = son.next;
			son.next = parent;
			parent = son;
			son = sonson;
		}
		return parent;
	}

	static class ListNode {
		int val;
		ListNode next;

		ListNode() {
		}

		ListNode(int val) {
			this.val = val;
		}

		ListNode(int val, ListNode next) {
			this.val = val;
			this.next = next;
		}
	}

}

 

 

题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值