Java链表笔记总结
文章来源:
代码随想录
以下笔记是我在训练营学习代码随想录的思路和解题过程中自己的总结和思考,可能会有误
203.移除链表元素
思路(虚拟结点)
- 新建一个指向头节点的虚拟节点
- 新建一个表明当前位置的节点,用以遍历链表,起始点在虚拟节点处
- 在遍历过程中,若当前节点的下一个节点值为目标元素,则跳过该下一个节点,转而连接下下个节点
代码
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode dummy = new ListNode(); //新建一个指向头节点的虚拟节点
dummy.next = head;
ListNode cur = dummy; //表明当前位置的节点
while(cur.next != null){ //指向null说明已经到最后一个元素了,遍历结束
if(cur.next.val == val){
cur.next = cur.next.next;
}else{
cur = cur.next;
}
}
return dummy.next;
}
}
707.设计链表
代码
class MyLinkedList {
class Listnode{
int val;
Listnode next;
Listnode(int val){
this.val = val;
}
}
private int size;
private Listnode head;
//初始化链表
public MyLinkedList() {
this.size = 0; //初始化链表大小 为0
this.head = new Listnode(0); //初始化头节点,为0,Listnode(0)为上面Class定义的Listnode方法
}
public int get(int index) {
if(index < 0 || index >= size){
return -1;
}
Listnode cur = head;
for(int i =0; i <= index ; i++){
cur = cur.next;
}
return cur.val;
}
public void addAtHead(int val) {
Listnode newnode = new Listnode(val);
newnode.val = val;
newnode.next = head.next;
head.next = newnode;
size++;
}
public void addAtTail(int val) {
Listnode newnode = new Listnode(val);
Listnode cur = head;
while(cur.next != null){
cur = cur.next;
}
cur.next = newnode;
size++;
}
public void addAtIndex(int index, int val) {
Listnode newnode = new Listnode(val);
Listnode cur = head;
if (index < 0 || index > size) {
return;
}
while(index > 0){
cur = cur.next;
index--;
}
newnode.next = cur.next;
cur.next = newnode;
size ++;
}
public void deleteAtIndex(int index) {
if (index < 0 || index >= size) {
return;
}
Listnode cur = head;
for(int i = 0; i<index; i++){
cur = cur.next;
}
cur.next = cur.next.next;
size --;
}
}
/**
* Your MyLinkedList object will be instantiated and called as such:
* MyLinkedList obj = new MyLinkedList();
* int param_1 = obj.get(index);
* obj.addAtHead(val);
* obj.addAtTail(val);
* obj.addAtIndex(index,val);
* obj.deleteAtIndex(index);
*/
206反转链表
代码(双指针法)
public ListNode reverseList(ListNode head) {
// 1. 初始化指针
ListNode left = null; // 初始时,第一个节点反转后指向null
ListNode cur = head; // 从原链表的头节点开始处理
ListNode right = null; // 用来临时保存当前节点的下一个节点
// 2. 遍历整个链表,直到当前节点为空
while (cur != null) {
// 步骤1:保存当前节点的下一个节点到right
right = cur.next;
// 作用:改变cur.next指向后,我们会丢失原有的后继节点,所以必须提前存下来,保证后续能继续遍历
// 步骤2:反转当前节点的指针方向
cur.next = left;
// 作用:让当前节点的next指向它的前驱节点(left),完成一次局部反转
// 步骤3:移动left指针到当前节点
left = cur;
// 作用:当前节点处理完成,下一个节点的前驱就是当前节点,所以left需要后移
// 步骤4:移动cur指针到下一个节点
cur = right;
// 作用:继续处理下一个节点,right是之前保存的原后继节点
}
// 3. 返回反转后的新头节点
return left;
// 作用:循环结束时,cur为null,left就是原链表的最后一个节点,也就是反转后的新头节点
}




216

被折叠的 条评论
为什么被折叠?



