移除链表元素为基础题,需要注意的就是ptr移动指针最后需要停在被移除指针前一结点,java中没有引用的地址会被垃圾处理机收集,不需要释放被移除指针的空间。
/**
* 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) {
ListNode ptr=new ListNode(-1,head);
ListNode newhead=ptr.next;
while(ptr!=null){
if(ptr.next!=null&&ptr.next.val==val){
if(ptr.next==newhead){
newhead=ptr.next.next;
}
ptr.next=ptr.next.next;
}else{
ptr=ptr.next;
}
}
return newhead;
}
}
基础题,考研对链表原理的掌握以及模拟链表的各种操作。
class MyLinkedList {
int size;
ListNode head;
public MyLinkedList() {
size=-1;
head=new ListNode(0);
}
public int get(int index) {
ListNode ptr=head;
if(index>size)
return -1;
while(index-->=0)
ptr=ptr.next;
return ptr.val;
}
public void addAtHead(int val) {
addAtIndex(-1,val);
}
public void addAtTail(int val) {
ListNode newend=new ListNode(val);
int i=size;
ListNode end=head;
while(i-->=0)
end=end.next;
end.next=newend;
++size;
}
public void addAtIndex(int index, int val) {
if(index>size)
{
if(index==size+1){
addAtTail(val);
return;
}
else{
return;
}
}
ListNode ptr=head;
while(index-->0){
ptr=ptr.next;
}
ListNode insert=new ListNode(val);
insert.next=ptr.next;
ptr.next=insert;
++size;
}
public void deleteAtIndex(int index) {
if(index>size)
return;
ListNode ptr=head;
while(index-->0){
ptr=ptr.next;
}
ptr.next=ptr.next.next;
--size;
}
}
class ListNode{
int val;
ListNode next;
public ListNode(int val){
this.val=val;
}
}
直接进行反转的模拟,注意在进行指针的反转时,喜欢先把原指向的下一结点进行备份,再进行翻转。图解中清晰看出,随着reverse指针移动到5后面的空指针,此时newhead恰好正是反转链表的头节点。
代码如下
class Solution {
public ListNode reverseList(ListNode head) {
ListNode newhead=null;
ListNode reverse=head;
while(reverse!=null){
ListNode copy=reverse.next;
reverse.next=newhead;
newhead=reverse;
reverse=copy;
}
return newhead;
}
}