翻转链表

描述

给定一个单链表的头结点pHead,长度为n,反转该链表后,返回新链表的表头。
 
数据范围: n1000
要求:空间复杂度 O(1),时间复杂度 O(n) 。
 
如当输入链表{1,2,3}时,
经反转后,原链表变为{3,2,1},所以对应的输出为{3,2,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 newN = null;
        ListNode s = head;
        while(s!=null){
            ListNode nextp = s.next;
            s.next=newN;
            newN=s;
            s = nextp;
        }
        return newN;
    }
}

方式二

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

ListNode(int val) {
this.val = val;
}
}*/
import java.util.Stack;
public class Solution {
    public ListNode ReverseList(ListNode head) {
        if(head == null || head.next==null) return head;
        Stack<ListNode> stackP = new Stack<>();
        while(head!=null){
            stackP.push(head);
            head = head.next;
        }
        head = stackP.pop();
        ListNode lastP = head;
        while(!stackP.isEmpty()){
            lastP.next=stackP.pop();
            lastP=lastP.next;
        }
        lastP.next=null;
        return head;
    }
}
posted @ 2021-12-08 16:39  始是逍遥人  阅读(49)  评论(0编辑  收藏  举报