算法面试3---链表

此生再无相见时 提交于 2019-11-29 18:23:23

1 链表反转

例1:LeetCode 206。本题虽然简单但却是众多公司的面试问题。反转前后的图示如下:

 在反转的过程中主要是依据指针之间的移动,如下图所示:

 

class Solution {

    public ListNode reverseList(ListNode head) {
        ListNode prev = null;
        while (head != null) {
            //1 每次修改前先把head.next备份否则head修改后找不到head.next
            ListNode nextTemp = head.next; 
            //2 修改head.next temp用来保存的是上次头节点的信息
            head.next = prev;
            //3 temp进行更新保存此次头节点的信息
            prev = head;
            //4 继续进行遍历
            head = nextTemp;
        }    
        //返回新链表的头结点
        return prev;        
    }
        
}

//递归版本的实现
class Solution {
    
    public ListNode reverseList(ListNode head) {
        //递归的终止条件
        if (head == null || head.next == null) return head;
        //递归处理的操作是从最后一个元素开始的
        ListNode p = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return p;
    }
}

与此类似的有题目:LeetCode:92

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!