牛客网-反转链表

136 阅读1分钟

题目描述

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

解法1

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode ReverseList(ListNode head) {
        
        if(head == null || head.next==null){
            return head;
        }
        
        
        ListNode left=head;
        ListNode mid=left.next;
        ListNode right = mid.next;
        
        while(right!=null){
            mid.next = left;
                        
            left = mid;
            mid = right;
            right = right.next;
        }
        
        mid.next = left;
        head.next = null;
        head = mid;
        
        return head;
    }
}

解法2

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode ReverseList(ListNode head) {
        if(head==null || head.next==null){
            return head;
        }
        
        ListNode newListNode=null;
        
        while(head!=null){
            
            //把源链表进行头插法到新的node中
            ListNode old_head = head;
            head = head.next;

            old_head.next = newListNode;
            newListNode = old_head;
        }
        
        return newListNode;
        
    }
}

我的博客即将同步至腾讯云+社区,邀请大家一同入驻:cloud.tencent.com/developer/s…