【Java面试题】反转链表

【题目】:
输入一个链表,反转链表后,输出新链表的表头。

【示例】:

abcd

反转:

结果:dbca

【关键点】: 链表

【Java】:

/*
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 pre = null; // 当前节点的前一个节点
        ListNode next = null; // 当前节点的下一个节点
        while( head != null){
            next = head.next; // 记录当前节点的下一个节点位置;
            head.next = pre; // 让当前节点指向前一个节点位置,完成反转
            pre = head; // pre 往右走
            head = next;// 当前节点往右继续走
        }
        return pre;
    }
}

发布了195 篇原创文章 · 获赞 335 · 访问量 12万+

猜你喜欢

转载自blog.csdn.net/cungudafa/article/details/101165114
今日推荐