链表节点
public class LinkedlistNode {
public int Value;
public LinkedlistNode next;
public LinkedlistNode(int Value) {
this.Value = Value;
}
}
利用数组快速搭建链表
public class BuildLinkedlist {
public LinkedlistNode buildLinkedlist(int[] arr) {
LinkedlistNode head = new LinkedlistNode(arr[0]);
LinkedlistNode node = head;
for (int i = 1; i < arr.length; i++) {
node.next = new LinkedlistNode(arr[i]);
node=node.next;
}
return head;
}
}
O(1)时间内删除指定节点
public void deleteNode(LinkedlistNode head,LinkedlistNode node) {
if (node.next == null) {//判断当前节点是否为尾结点,尾结点时时间复杂度为O(n)
if (head == node) {//链表中只有单个节点,头尾节点相同
head = null;
node = null;
} else {
LinkedlistNode temp=head;
while (temp.next != node) {
temp=temp.next;
}
temp.next=null;
}
return;
}
node.Value=node.next.Value;//复制下一节点的值
LinkedlistNode temp=node.next;//存储下一点
node.next=temp.next;//当前节点指向下下一节点
temp.next=null;//下一节点的next指针置为空值(即删除下一节点)
}
一次遍历查找倒数第K个节点
public LinkedlistNode findNode(int k, LinkedlistNode head) {
if (head == null) {
return null;
}
if (k <= 0) {
return null;
}
LinkedlistNode temp1=head;//前指针
LinkedlistNode temp2=head;//后指针
int count=-1;
while (temp1 != null) {
temp1=temp1.next;
if (++count >= k) {//后指针在前指针移动k次后开始移动
temp2=temp2.next;
}
}
if (k > count+1) {//当k大于实际链表长度时
return null;
}
return temp2;
}
查找链表中环的入口节点
public LinkedlistNode findNode2(LinkedlistNode head) {
if (head == null||head.next==null) {
return null;
}
LinkedlistNode temp1 = head.next;//前指针
LinkedlistNode temp2 = head;//后指针
do {
temp1 = temp1.next.next;//前指针走两步
temp2 = temp2.next;//后指针走一步
if (temp1 == null) {//不存在环
return null;
}
}
while (temp1 != temp2);//通过第一次相遇找到环中一个节点
int count=0;
do {
temp1 = temp1.next;
count++;//记录环中节点数目
} while (temp1 != temp2);//通过第二次相遇计算出环中节点数目
temp1=head;
temp2=head;
do {
temp1=temp1.next;
if (--count < 1) {
temp2=temp2.next;
}
}
while (temp1.next != temp2);//通过第三次相遇得到环的入口节点
return temp2;
}
链表反转
public LinkedlistNode reverseList(LinkedlistNode head) {
if (head == null) {
return null;
}
if (head.next == null) {
return head;
}
LinkedlistNode temp1=head.next.next;//定义三个指针缓存相邻三个节点
LinkedlistNode temp2=head.next;
LinkedlistNode temp3=head;
temp3.next=null;
temp2.next=temp3;
while (temp1 != null) {
temp3=temp2;
temp2=temp1;
temp1=temp1.next;
temp2.next=temp3;
}
return temp2;
}
合并两个有序的链表
public LinkedlistNode merge(LinkedlistNode head1, LinkedlistNode head2) {
if (head1 == null) {
return head2;
} else if (head2 == null) {
return head1;
}
LinkedlistNode node1=head1;//链表1头指针
LinkedlistNode node2=head2;//链表2头指针
LinkedlistNode node;//合并后链表头指针
if (node1.Value < node2.Value) {
node = node1;
node.next = merge(node1.next, node2);
} else {
node = node2;
node.next=merge(node1, node2.next);
}
return node;
}