反转链表

反转链表

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

代码实现

package 剑指offer;

/**
 * @author WangXiaoeZhe
 * @Date: Created in 2019/11/22 15:46
 * @description:
 */

public class Main7 {
    public static void main(String[] args) {

    }

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

        ListNode(int val) {
            this.val = val;
        }
    }

    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;
    }
}
posted @ 2019-11-22 15:57  π。  阅读(108)  评论(0编辑  收藏  举报