LeetCode面试常考算法——链表
- 反转链表 LeetCode
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
【解题关键】以其中一个节点为例,反转其实是将当前节点的next指针指向当前节点的前驱节点。反转链表其实是将所有节点都反转一遍。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode next = null;
while(head != null){
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
}
- 环形链表I LeetCode
【解法一】0.5s或者1s不断遍历next,如果可以走到头,也就是说next为null,无环;如果走不到头,有环。
【解法二】使用Set来判重。遍历链表,将每个ListNode都加到Set中,一直遍历到链表尾部,如果Set中存在ListNode,则有环,不存在则无环。
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
Set<ListNode> set = new HashSet<>();
while (head != null) {
if (set.contains(head)) {
return true;
}
set.add(head);
head = head.next;
}
return false;
}
}
【解法三】快慢指针法,快指针每次走两步,慢指针每次走一步;两个指针如果可以相遇则有环,不能相遇则无环;
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
/*双指针:快慢指针*/
if(head == null || head.next == null){
return false;
}
ListNode slow = head.next;
ListNode fast = head.next.next;
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
if(slow == fast){
return true;
}
}
return false;
}
}
- 环形链表II LeetCode
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
if(slow == fast){
ListNode slow2 = head;
while (slow2 != slow){
slow = slow.next;
slow2 = slow2.next;
}
return slow;
}
}
return null;
}
}
由于博主也是在攀登的路上,文中可能存在不当之处,欢迎各位多指教! 如果文章对您有用,那么请点个”推荐“,以资鼓励!
欢迎各位加我主页weixin,备注“博客园”,进入技术交流群,和我一起讨论和交流,共同进步!

浙公网安备 33010602011771号