剑指offer:反转链表

2018-04-05  本文已影响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;
        
    }
}
上一篇 下一篇

猜你喜欢

热点阅读