• LeetCode_206. Reverse Linked List


    206. Reverse Linked List

    Easy

    Reverse a singly linked list.

    Example:

    Input: 1->2->3->4->5->NULL
    Output: 5->4->3->2->1->NULL
    

    Follow up:

    A linked list can be reversed either iteratively or recursively. Could you implement both?

    package leetcode.easy;
    
    /**
     * Definition for singly-linked list. public class ListNode { int val; ListNode
     * next; ListNode(int x) { val = x; } }
     */
    public class ReverseLinkedList {
    	private static void print(ListNode head) {
    		if (head == null) {
    			return;
    		}
    		while (head != null) {
    			System.out.print(head.val);
    			if (head.next != null) {
    				System.out.print("->");
    			}
    			head = head.next;
    		}
    		System.out.println("->NULL");
    	}
    
    	public ListNode reverseList(ListNode head) {
    		ListNode nextNode = null;
    		ListNode curr = head;
    		while (curr != null) {
    			ListNode tempNext = curr.next;
    			curr.next = nextNode;
    			nextNode = curr;
    			curr = tempNext;
    		}
    		return nextNode;
    	}
    
    	@org.junit.Test
    	public void test() {
    		ListNode ln1 = new ListNode(1);
    		ListNode ln2 = new ListNode(2);
    		ListNode ln3 = new ListNode(3);
    		ListNode ln4 = new ListNode(4);
    		ListNode ln5 = new ListNode(5);
    		ln1.next = ln2;
    		ln2.next = ln3;
    		ln3.next = ln4;
    		ln4.next = ln5;
    		ln5.next = null;
    		print(ln1);
    		print(reverseList(ln1));
    	}
    }
    
  • 相关阅读:
    Java集合之LinkedHashMap
    ConcurrentHashMap原理分析
    Java集合之HashMap
    JAVA集合之ArrayList
    Python内建函数
    Vscode 安装Java Spring项目
    音频质量评估-2
    音频质量评估-1
    Python list 实现
    怎么测试大数据
  • 原文地址:https://www.cnblogs.com/denggelin/p/11731025.html
Copyright © 2020-2023  润新知