美文网首页
反转链表

反转链表

作者: 上杉丶零 | 来源:发表于2019-12-14 05:03 被阅读0次

    输入一个链表,反转链表后,输出新链表的表头。

    package 剑指Offer.反转链表;
    
    public class Solution {
        public ListNode ReverseList(ListNode head) {
            if (head == null || head.next == null) {
                return head;
            }
    
            ListNode current = head;
            ListNode next = null;
            ListNode previous = null;
    
            while (current != null) {
                next = current.next;
                current.next = previous;
                previous = current;
                current = next;
            }
    
            return previous;
        }
    }
    
    class ListNode {
        int val;
        ListNode next = null;
    
        ListNode(int val) {
            this.val = val;
        }
    }
    

    相关文章

      网友评论

          本文标题:反转链表

          本文链接:https://www.haomeiwen.com/subject/sfxcnctx.html