class Node {
Node next;
int data;
public Node(int data) {
this.data = data;
}
public Node(){}
public Node(Node next, int data) {
super();
this.next = next;
this.data = data;
};
}
/**
* 随便给一个节点,要你删除该节点【尾节点不适应】
* @param node
* @return
*/
public static Boolean deleteUnknown(Node node){
if(node == null || node.next == null ){
return false;
}else{
node.data = node.next.data;
node.next = node.next.next;
return true;
}
}
/**
* 寻找单链表的中间节点
* @param head
* @return 当Length为偶数的时候,慢指针指向的节点和其下一个节点都是中间节点
*/
public static Node middleNode(Node head){
Node middle = head; //慢指针
Node tempMiddle = head;//快指针
while(tempMiddle != null
&& tempMiddle.next != null
&& tempMiddle.next.next != null){
middle = middle.next;
tempMiddle = tempMiddle.next.next;
}
return middle;
}
/**
* 从尾到头输出链表的节点【运用递归】
* @param head
*/
public static void rollPrint(Node head){
if(head != null){
rollPrint(head.next);
System.out.print(head.data+" ");
}
}
/**
* 输入一个链表的头结点,反转该链表并输出反转后链表的头结点
* @param head链表的头结点
* @return反转后的链表的头结点
*/
public static Node rollBack(Node head){
// 创建一个临时结点,当作尾插法的逻辑头结点
Node First = new Node();
First.next = null;
Node cur = head; //保证原链表不受影响
Node nex = null;
while(cur != null){
nex = cur.next;
cur.next = First.next;//交换链表的next值
First.next = cur;
cur = nex;
}
return First.next;
}
/**
* 寻找链表中的倒数第K个数字【窗口移动的思路】
* @param num返回相应的数值
* @return超出范围返回为-1
*/
public static int kValue(int num) {
//注意边界
if (num < 1 || num > Length())
return -1;
Node first = head;
Node last = head;
//利用两个指针来定位倒数第K个数字
for (int i = 0; i < num; i++) {
last = last.next;
}
while(last != null){
first = first.next;
last = last.next;
}
return first.data;
}
/**
* 插入排序
*/
public static void sortNode() {
Node cur = head;
Node next = null;
int temp = 0;
while (cur != null) {
next = cur.next;
while (next != null) {
if (next.data > cur.data) {
temp = next.data;
next.data = cur.data;
cur.data = temp;
}
next = next.next;
}
cur = cur.next;
}
}
链表常见的面试题
最新推荐文章于 2022-04-06 17:17:52 发布