您的位置:首页 > 职场人生

【面试题16】反转链表

2017-06-12 10:31 197 查看
题目:

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

分析:

反转链表只需改变链接方向,改变方向时需要将原本指向后一个结点的链接方向指向前一个结点,因此需要记录下三个结点。

实现:(非递归)

public ListNode ReverseList(ListNode head) {  
    ListNode cur = head;  
    ListNode next = null;  
    ListNode pre = null;  
    if (head == null || head.next == null) {  
        return head;  
    }  
    while (cur != null) {  
        next = cur.next;  
        // 改变链方向  
        cur.next = pre;  
        // 移动结点,继续操作  
        pre = cur;  
        cur = next;  
    }  
    return pre;  
}  

实现:递归:

public ListNode Reverse(ListNode head) {  
    if (head == null || head.next == null) {  
        return head;  
    }  
    ListNode secondElem = head.next;  
    head.next = null;  
    ListNode reverseRest = Reverse(secondElem);  
    secondElem.next = head;  
    return reverseRest;  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: