一、常见面试题如下
①单链表反转
②链表中环的检测
③两个有序的链表合并
④删除链表倒数第n个结点
⑤求链表的中间结点
二、单链表反转
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
1、递归法实现
/**
* 单链表反转
*/
public class LinkList {
private static class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
}
}
/**
* 递归法是从最后一个Node开始,在谈栈的过程中将指针顺序置换
*
* @param head
* @return
*/
public static Node reverse(Node head) {
//递归终止条件是当前为空,或者下一个节点为空
if (head == null || head.next == null) {
return head;
}
//递归调用来反转每一个节点
Node cur = reverse(head.next);
//每一个节点是怎么反转的
head.next.next = head;
//防止循环链表,需要将head.next设置为空
head.next = null;
//每层递归都返回cur,也就是最后一个节点
return cur;
}
public static void main(String[] args) {
//1->2->3->4
Node node1 = new Node(1);
Node node2 = new Node(2);
Node node3 = new Node(3);
Node node4 = new Node(4);
node1.nex