《剑指offer》——反转链表(Java)

题目描述

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

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

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode ReverseList(ListNode head) {

    }
}

思路:

pre =null

next =null


1->2->3->null

1->pre nex->2->3->null

null<-1<-pre  next->2->3->null


null<-1<-pre->2    next->3->null

null<-1<-2<-pre    next->3->null


null<-1<-2<-pre->3   next->null

null<-1<-2<-3<-pre   next->null


null<-1<-2<-3

实现:

/*
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)
            return null;
        ListNode pre = null;
        ListNode next = null;
        while (head != null){
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;

    }
}
发布了83 篇原创文章 · 获赞 22 · 访问量 2220

猜你喜欢

转载自blog.csdn.net/love_MyLY/article/details/103484052