Java-单链表反转

用java实现单链表反转
定义三个指针pre cur post 分别指向前一个,当前和下一个节点
通过改变每个节点指向下一个节点的指针来达到反转链表的目的

在这里插入图片描述
具体代码实现:

class ListNode<T> {
    public T val;
    public ListNode<T> next;
    public ListNode(T val){
        this.val = val;
        this.next = null;
    }
}

public class ReversalList {
    public static ListNode<Integer> reverseList(ListNode<Integer> head){
        if(head==null || head.next==null)
            return head;
        ListNode<Integer> pre = null;
        ListNode<Integer> cur = head;
        ListNode<Integer> post= head.next;
        while(true){
            cur.next = pre;
            pre = cur;
            cur = post;
            if(post!=null)
                post = post.next;
            else
                return pre;
        }
    }
   
}

注意while循环中if判断顺序,最终结果返回的是pre节点

发布了37 篇原创文章 · 获赞 11 · 访问量 3900

猜你喜欢

转载自blog.csdn.net/Alphr/article/details/104619134