美文网首页
剑指offer:反转链表

剑指offer:反转链表

作者: 衣介书生 | 来源:发表于2018-04-05 14:57 被阅读6次

题目分析

输入一个链表,反转链表后,输出链表的所有元素。

代码

/*
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;
        }
        // 只有一个头结点
        if(head.next == null) {
            return head;
        }
        // 定义一个哑结点辅助
        ListNode dummy = new ListNode(0);
        ListNode temp = head;
        
        while(head != null) {
            head = head.next;
            temp.next = dummy.next;
            dummy.next = temp;
            temp = head;
        }
        
        return dummy.next;
        
    }
}

相关文章

网友评论

      本文标题:剑指offer:反转链表

      本文链接:https://www.haomeiwen.com/subject/lejyfftx.html