单向链表算法
2020-06-02 本文已影响0人
万福来
单向链表
反转单向链表
static Node reverseByRecursion(Node head) {
if (head == null || head.next == null) {
return head;
}
Node newHead = reverseByRecursion(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
static Node reverseByLoop(Node head) {
if (head == null || head.next == null) {
return head;
}
Node preNode = null;
Node nextNode;
while (head != null) {
nextNode = head.next;
head.next = preNode;
preNode = head;
head = nextNode;
}
return preNode;
}
单链表查找倒数第k个节点
static Node findKnode(Node head, int k) {
if (k < 1 || k > length(head)) {
return null;
}
Node p1 = head;
Node p2 = head;
for (int i = 0; i < k - 1; i++) {
p2 = p2.next;
}
while (p2.next != null) {
p2 = p2.next;
p1 = p1.next;
}
return p1;
}
单链表递归倒序打印
public static void printListReversely(Node head) {
if (head != null) {
printListReversely(head.next);
if (head != null) {
System.out.println(head.data);
}
}
}
单链表排序
public static void sort(Node head) {
Node currentNode;
Node nextNode;
for (currentNode = head; currentNode.next != null; currentNode = currentNode.next) {
for (nextNode = head; nextNode.next != null; nextNode = nextNode.next) {
if (nextNode.data > nextNode.next.data) {
int temp = nextNode.data;
nextNode.data = nextNode.next.data;
nextNode.next.data = temp;
}
}
}
}
单链表删除重复节点
public static void removeDuplicate(Node head) {
HashSet set = new HashSet();
Node temp = head;
Node pre = null;
while (temp != null) {
if (set.contains(temp.data)) {
pre.next = temp.next;
} else {
set.add(temp.data);
pre = temp;
}
temp = temp.next;
}
}