單向鏈表
反轉(zhuǎn)單向鏈表
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;
}
單鏈表查找倒數(shù)第k個(gè)節(jié)點(diǎn)
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;
}
}
}
}
單鏈表刪除重復(fù)節(jié)點(diǎn)
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;
}
}