zoukankan      html  css  js  c++  java
  • 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;
            
        }
    }
    
    
  • 相关阅读:
    BZOJ2337 [HNOI2011]XOR和路径
    「学习笔记」3.31代码学习
    uva live 12846 A Daisy Puzzle Game
    Cannot use ImageField because Pillow is not installed
    Android点击Button水波纹效果
    hdu 1241 Oil Deposits
    c++ 字符输入读取
    clutter recoder
    C/C++获取数组长度
    vector array and normal stanard array
  • 原文地址:https://www.cnblogs.com/sansamh/p/9959592.html
Copyright © 2011-2022 走看看