移除链表元素-day03
203. 移除链表元素
题目链接:https://leetcode.cn/problems/remove-linked-list-elements/description/
思路:在原来的链表中新增一个节点,这个节点作为头结点(好处,不用单独处理原链表的头结点)
代码:
public ListNode removeElements(ListNode head, int val) {
//设置一个虚拟的头结点
ListNode dummy=new ListNode();
dummy.next=head; //dummy作为头结点
ListNode cur=dummy;//重点
while(cur.next!=null){
if(cur.next.val==val){
cur.next=cur.next.next; //移除值是val的的结点
}else{
cur=cur.next; // cur指向下一个结点
}
}
return dummy.next;//返回异常val值的新链表
}
707. 设计链表
题目链接:https://leetcode.cn/problems/design-linked-list/description/
代码:
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;
this.head=new ListNode(0);
}
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.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) {
if(index<0 || index>size){
return;
}
ListNode pre=head;
for(int i=0;i<index;i++){
pre=pre.next;
}
ListNode newNode=new ListNode(val);
newNode.next=pre.next;
pre.next=newNode;
size++;
}
public void deleteAtIndex(int index) {
if(index<0 || index>=size){
return;
}
ListNode pre=head;
for(int i=0;i<index;i++){
pre=pre.next;
}
pre.next=pre.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. 反转链表
题目链接:https://leetcode.cn/problems/reverse-linked-list/description/
思路: 类似于快慢指针,cur快指针,pre是慢指针,temp作为中间变量
代码:
public ListNode reverseList(ListNode head) {
ListNode cur=head,pre=null;
while(cur!=null){
ListNode temp=cur.next;//当前结点的下一个结点
cur.next=pre;//执向当前结点的前一个结点
pre=cur;//执向当前结点
cur=temp;//执向当前结点的下一个结点
}
return pre;
}

浙公网安备 33010602011771号