Live2D

反转链表(Java)

/*      题目描述
      输入一个链表,反转链表后,输出新链表的表头。
      示例1
      输入
      {1,2,3}
      返回值
      {3,2,1}
      初始化:3个指针
      1)pre指针指向已经反转好的链表的最后一个节点,最开始没有反转,所以指向nullptr
      2)cur指针指向待反转链表的第一个节点,最开始第一个节点待反转,所以指向head
      3)nex指针指向待反转链表的第二个节点,目的是保存链表,因为cur改变指向后,后面的链表则失效了
      时间复杂度 O(1) 空间复杂度O(n)
*/
import java.util.ArrayList;
public class Solution {
    public ListNode ReverseList(ListNode head) {
        if(head==null){
            return null;
        }
        ListNode cur = head;
        ListNode pre = null;
        ListNode nex = null;
        
        while(cur != null){
            nex = cur.next;
            cur.next = pre;
            pre = cur;
            cur = nex;
        }
        
        return pre;
        
    }
}
posted @ 2021-01-19 16:41  细雪之舞0213  阅读(116)  评论(0)    收藏  举报