大家好呀,本博客目的在于記錄暑假學習打卡,后續會整理成一個專欄,主要打算在暑假學習完數據結構,因此會發一些相關的數據結構實現的博客和一些刷的題,個人學習使用,也希望大家多多支持,有不足之處也請指出,謝謝大家。
一,203.移除鏈表元素
. - 力扣(LeetCode)
方法一:定義新鏈表
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}* ListNode(int val) { this.val = val; }* ListNode(int val, ListNode next) { this.val = val; this.next = next; }* }*/
class Solution {public ListNode removeElements(ListNode head, int val) {if (head == null)return head;ListNode newtail = head;ListNode newhead = new ListNode();ListNode cur = newhead;while (newtail != null) {if (newtail.val != val) {cur.next = newtail;cur = newtail;newtail = newtail.next;} else {if (newtail.next == null)cur.next = null;newtail = newtail.next;}}return newhead.next;}
}
方法二:在原鏈表基礎上刪除
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}* ListNode(int val) { this.val = val; }* ListNode(int val, ListNode next) { this.val = val; this.next = next; }* }*/
class Solution {public ListNode removeElements(ListNode head, int val) {if (head == null)return head;ListNode prev = head;ListNode pcur = head.next;while (pcur != null) {if (pcur.val == val) {prev.next = pcur.next;pcur = pcur.next;} else {prev = pcur;pcur = pcur.next;}}if(head.val==val)head=head.next;return head;}
}
二,206.反轉鏈表
. - 力扣(LeetCode)
采用了把后面的節點頭插到頭節點前面的方式
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}* ListNode(int val) { this.val = val; }* ListNode(int val, ListNode next) { this.val = val; this.next = next; }* }*/
class Solution {public ListNode reverseList(ListNode head) {if (head == null)return head;ListNode cur = head.next;head.next = null;ListNode curN;while (cur != null) {curN = cur.next;cur.next = head;head = cur;cur = curN;}return head;}
}
三,876鏈表的中間節點
. - 力扣(LeetCode)
運用了快慢指針
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}* ListNode(int val) { this.val = val; }* ListNode(int val, ListNode next) { this.val = val; this.next = next; }* }*/
class Solution {public ListNode middleNode(ListNode head) {if(head==null)return head;ListNode fast=head;ListNode slow=head;while(fast!=null&&fast.next!=null){fast=fast.next.next;slow=slow.next;}return slow;}
}
四,面試題02.02 返回倒數第k個節點
. - 力扣(LeetCode)
采用快慢指針
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode(int x) { val = x; }* }*/
class Solution {public int kthToLast(ListNode head, int k) {if(head==null)return -1;ListNode fast=head;ListNode slow=head;int count=0;while(count!=k-1){fast=fast.next;count++;}while(fast.next!=null){fast=fast.next;slow=slow.next;}return slow.val;}
}
本期博客就到這里,感謝閱讀