- 合并:通过定义两个链表指针,分别遍历两个两个链表,然后通过对比链表值的大小,确定哪个连接在谁的后面,然后较小的哪个指针接着向后移,然后再对比重复以上操作,直到指针指向null。
if(list1 == null) return list2; if(list2 == null) return list1; ListNode resultNode = new ListNode(0); ListNode p = resultNode; while(list1 != null && list2 != null) { if(list1.val < list2.val) { p.next = list1; list1 = list1.next; } else { p.next = list2; list2 = list2.next; } p = p.next;//更新p节点连接位置 } if(list1 != null) { p.next = list1; } if(list2 != null) { p.next = list2; } return resultNode.next;
- 删除:通过指针比较前后两者是否相同,不相同则指针向后移动,相同则通过指针直接跳过相同,直接接到相同值的下一个数值上。
if (head == null || head.next == null) return head; ListNode p = head; while (p != null && p.next != null) { if (p.val == p.next.val) { p.next = p.next.next; } else { p = p.next; } } return head;
- 环形:通过设定两个指针,一个快指针和一个慢指针,快指针每次移动两个,而慢指针每次移动一个,当快指针和慢指针相遇的时候就表明这个链表存在环。
if(head == null) return false; ListNode fastPt = head ; ListNode slowPt = head ; while(fastPt != null && fastPt.next != null){ slowPt = slowPt.next; fastPt = fastPt.next.next; if(slowPt == fastPt){ return true; } } return false;
- 相交:同样定义两个指针,当两个指针前后出现了相同的值时表明他们是相交的。
ListNode a = headA; ListNode b = headB; if(headA == null) return null; if(headB == null) return null; while(a != b){ a = a == null ? headB : a.next; b = b == null ? headA : b.next; } return a;
- 反转:定义两个指针,一个空指针,一个头指针,就是通过将头指针指向下一个数后,通过空指针指向前面的数以达到反转的效果。
ListNode A = null; ListNode B = head; while(B!=null){ ListNode next = B.next; B.next = A; A = B; B = next; } return A;
- 回文:同样快慢指针,确定中间位置,在中间位置对右侧的链表进行反转,接着对比两个链表即可。
- 中间节点:两个指针,一个快指针,一个慢指针,同样一个每次移动两个一个每次移动一个,当快指针移动到null时,慢指针也同时达到了中间位置,输出即可。
ListNode first = head; ListNode second = head; while(first != null && first.next != null){ second= second.next; first = first.next.next; } return second;
链表算法题目
最新推荐文章于 2024-07-14 19:56:17 发布