定义链表结构
1、 单链表
public static class Node{
public int value;
public Node next;
public Node(int data){
value = data;
}
}
2、双链表
public static class DoubleNode{
public int value;
public DoubleNode last;
public DoubleNode next;
public DoubleNode(int data) {
value = data;
}
}
打印链表的值
1、单链表
public static void printLinedList(Node head){
System.out.print("Linked List:");
while(head != null){
System.out.print(head.value + " ");
head = head.next;
}
System.out.println();
}
2、双链表
public static void printDoubleLinkedList(DoubleNode head) {
System.out.print("Double Linked List:");
DoubleNode end = null;
while(head != null) {
System.out.print(head.value + " ");
end = head;
head = head.next;
}
System.out.print("|");
while(end != null) {
System.out.print(end.value + " ");
end = end.last;
}
System.out.println();
}
反转单向链表(重要)
public static Node reverseList(Node head) {
Node pre = null;
Node next = null;
while(head != null) {
//记录当前节点的下一个节点
next = head.next;
//当前节点指向pre
head.next = pre;
//pre和head向前进一位
pre = head;
head = next;
}
return pre;
}
反转双链表
public static DoubleNode reverseList(DoubleNode head) {
DoubleNode pre = null;
DoubleNode next = null;
while(head != null) {
next = head.next;
head.next = pre;
head.last = next;
pre = head;
head = next;
}
return pre;
}
判断单链表是否有环,并且返回入环的第一个节点
public ListNode detectCycle(ListNode head) {
if(head == null || head.next == null) return null;
ListNode slow = head, fast = head, start = head;
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
if(slow == fast){
while(slow != start){
slow = slow.next;
start = start.next;
}
return start;
}
}
return null;
}
相交链表
在这里插入代码片