• leetcode 206. Reverse Linked List


    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?
    
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        //每次循环next节点时 用next节点val创建新节点 更改节点指针
        public ListNode reverseList(ListNode head) {
            if (head == null || head.next == null) {
    		    return null;
    	    }
            ListNode newHead = new ListNode(head.val);
            ListNode sub = head.next;
            while (sub != null) {
                ListNode node = newHead;
                //创建新的节点 val是next节点的val
                ListNode node1 = new ListNode(sub.val);
                //新节点的next指针 指向前一个节点
                node1.next = node;
                //新节点赋给newHead
                newHead = node1;
                sub = sub.next;
            }
            return newHead;
            
        }
    }
    
    /**
     * 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) {
                return head;
            }
            ListNode pre = null;
            ListNode cur = head;
            ListNode next = head.next;
            
            while (cur != null) {
                next = cur.next;
                cur.next = pre;
                pre = cur;
                cur = next;
            }
            
            return pre;
            
        }
    }
    
    
  • 相关阅读:
    EL表达式
    JavaBean知识
    设计模型MVC和JavaBean
    JSP知识
    会话技术
    Servlet知识
    selenium+maven+testng+IDEA+git+jenkins自动化测试环境搭建(三)
    selenium+maven+testng+IDEA+git自动化测试环境搭建(二)
    selenium+testng+testng-xslt-1.1.2之报告完善
    selenium入门环境之浏览器问题
  • 原文地址:https://www.cnblogs.com/sansamh/p/9959592.html
Copyright © 2020-2023  润新知