链表是面试的时候最为基本的一个题目,而且关于链表的题目也相对来说比较简单,相关的题目:

    1.逆序打印链表

    2.链表反转,反转链表的指定部分,交换链表的相邻节点,交换相邻的K个节点

    3.查找链表的最大值,查找并删除链表倒数第N个节点,查询节点并删除,删除链表的重复节点,删除链表的所有重复节点

    4.判断旋转链表,回文链表

    5.链表划分,链表重新洗牌

    6.链表的排序(归并排序和插入排序),几个有序链表合并成为一个有序链表

    7.利用循环链表实现约瑟夫环,得到链表的交点,判断链表是否有环以及找到链表环的入口,利用链表环的思路解决数组环

1.逆序打印链表

  题目要求:给定单链表,从尾到头打印每个节点的值,不同的值之间用空格隔开,比如1->2->3->4->5,输出5 4 3 2 1。

  这道题有递归和非递归两种实现方式,非递归算法如下:

利用栈,从头到尾依次入栈,然后出栈并打印,代码如下:

  

    public void printInverse(ListNode head) {
        if (head.next == null) {
            return;
        }
        Stack<T> stack = new Stack<T>();
        ListNode<T> p = head.next;
        while (p != null) {
            stack.push(p.val);
            p = p.next;
        }
        while (!stack.isEmpty()) {
            System.out.println(stack.pop() + " ");
        }
        System.out.println();
    }

 

递归算法如下:

    public void printrecursive(ListNode<T> head) {
        if (head.next == null) {
            return;
        }
        recursive(head.next);
        System.out.println();
    }
    public void recursive(ListNode<T> p) {
        if (p != null) {
            recursive(p.next);
            System.out.print(p.val + " ");
        }
    }

 

2.链表反转,反转链表的指定部分,交换链表的相邻节点,交换相邻的K个节点

 

  首先是链表反转,有递归和非递归两种实现方式,对于非递归方式,首先要定要三个指针,pre表示前驱节点,p表示当前节点,next表示下一个节点,非递归的时候有非常固定的模式,next=p.next,p.next=pre,pre=p,p=next;具体有leetcode206. Reverse Linked List,具体的代码如下:

    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        } else {
            ListNode pre = head;
            ListNode p = head.next;
            ListNode next = null;
            while (p != null) {
                next = p.next;
                p.next = pre;
                pre = p;
                p = next;
            }
            head.next = null;
            return pre;
        }
    }

 

递归算法如下:

    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        } else {
            ListNode tail = recursive(head);
            head.next = null;
            return tail;
        }
    }
    
    public ListNode recursive(ListNode p) {
        if (p.next == null) {
            return p;
        } else {
            ListNode next = p.next;
            ListNode tail = recursive(next);
            next.next = p;
            return tail;
        }
    }

 ------------------------------------------------------------------------------------------------

 

  然后是反转链表的指定部分,具体的题目leetcode92. Reverse Linked List II,题目要求如下:

Reverse a linked list from position m to n. Do it in-place and in one-pass.

For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
View Code

相关文章: