通过编码实现单链表稍微复杂点的操作功能:
1 查找链表倒数最后的N节点
public Node findNodeLastTopN(Node head,int n ){ if(head == null||n<1){ return null; } Node previous = head; Node current = head; for(int i = 0;i<n-1;i++){ if(current == null){ return null; } current = current.next; } while(current.next!=null){ previous = previous.next; current = current.next; } return previous; }
2 删除链表中倒数最后的N节点
public Node deleteNodeLastTopN(Node head,int n ){ if(head == null||n<1){ return null; } Node first = head; Node second = head; for(int i = 0;i<n-1;i++){ if(second == null){ return null; } second = second.next; } while(second.next!=null){ first = first.next; second = second.next; } return first; }
3 判断链表中是否有环
public boolean nodeHasCycle(Node head){ if(head == null|| head.next == null){ return false; } Node slow,fast; fast = head.next; slow = head; while(fast!=slow){ if(fast==null||fast.next==null){ return false; } fast = fast.next.next; slow = slow.next; } return true; }
4 判断两个链表中是否有交点
public static boolean nodeIsIntersect(Node head1, Node head2) { if (head1 == null || head2 == null) { return false; } Node tail1 = head1; // 找到链表1的最后一个节点 while (tail1.next != null) { tail1 = tail1.next; } Node tail2 = head2; // 找到链表2的最后一个节点 while (tail2.next != null) { tail2 = tail2.next; } return tail1 == tail2; }
5 获取两个相交的链表第一个结点
public static Node getIntersectFirstNode(Node head1, Node head2) { if (head1 == null || head2 == null) { return null; } int len1 = 1; Node tail1 = head1; while (tail1.next != null) { tail1 = tail1.next; len1++; } int len2 = 1; Node tail2 = head2; while (tail2.next != null) { tail2 = tail2.next; len2++; } // 不相交直接返回NULL if (tail1 != tail2) { return null; } Node n1 = head1; Node n2 = head2; // 略过较长链表多余的部分 if (len1 > len2) { int k = len1 - len2; while (k != 0) { n1 = n1.next; k--; } } else { int k = len2 - len1; while (k != 0) { n2 = n2.next; k--; } } // 一起向后遍历,直到找到交点 while (n1 != n2) { n1 = n1.next; n2 = n2.next; } return n1; }
6 删除链表中重复的元素
public Node deleteRepeatNode(Node head){ if(head == null){ return null; } Node node = head; while(node.next != null){ if(node.data == node.next.data){ node.next = node.next.next; }else{ node = node.next; } } return head; }