203. 移除链表元素
给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。
链表基础题
public ListNode removeElements(ListNode head, int val) {
while(head!=null&&val==head.val){
head=head.next;
}
if(head==null)return head;
ListNode iterator=head;
while(iterator.next!=null){
if(iterator.next.val==val)
iterator.next=iterator.next.next;
else
iterator=iterator.next;
if(iterator==null)break;
}
return head;
}
206. 反转链表
做了无数遍了 。。。
public ListNode reverseList(ListNode head) {
ListNode node = null;
ListNode tmp=null;
while(head!=null){
tmp=head.next;
head.next=node;
node=head;
head=tmp;
}
return node;
}
707. 设计链表
实现一下链表结构 代码如下
写了一个单链表 一个双链表
单链表
class MyLinkedList {
class ListNode {
int val;
ListNode next;
public ListNode(){}
public ListNode(int val) {
this.val = val;
}
}
int size;
ListNode head;
public MyLinkedList() {
size=0;
head=new ListNode(0);
}
public int get(int index) {
if(index<0||index>=size)return -1;
ListNode t=head;
for (int i = 0; i <=index; i++) {
t=t.next;
}
return t.val;
}
public void addAtHead(int val) {
addAtIndex(0,val);
}
public void addAtTail(int val) {
addAtIndex(size,val);
}
public void addAtIndex(int index, int val) {
if(index>size)return ;
index=index<0?0:index;
ListNode t=head;
ListNode listNode = new ListNode(val);
for (int i = 0; i < index; i++) {
t=t.next;
}
listNode.next=t.next;
t.next=listNode;
size++;
}
public void deleteAtIndex(int index) {
if(index<0||index>=size)return;
ListNode t=head;
if(size==0){
head=head.next;
return;
}
for (int i = 0; i < index; i++) {
t=t.next;
}
t.next=t.next.next;
size--;
}
}
双链表
class MyLinkedList {
class ListNode {
int val;
ListNode next,pre;
public ListNode(){}
public ListNode(int val) {
this.val = val;
}
}
int size;
ListNode head,tail;
public MyLinkedList() {
size=0;
head=new ListNode(0);
tail=new ListNode(0);
head.next=tail;
tail.pre=head;
}
public int get(int index) {
if(index<0||index>=size)return -1;
ListNode t;
if(index<size/2){
t=head;
for (int i = 0; i <=index; i++) {
t=t.next;
}
return t.val;
}else{
t=tail;
for (int i = 0; i <size-index; i++) {
t=t.pre;
}
return t.val;
}
}
public void addAtHead(int val) {
addAtIndex(0,val);
}
public void addAtTail(int val) {
addAtIndex(size,val);
}
public void addAtIndex(int index, int val) {
if(index>size)return ;
index=index<0?0:index;
ListNode t=head;
ListNode listNode = new ListNode(val);
for (int i = 0; i < index; i++) {
t=t.next;
}
listNode.next=t.next;
t.next.pre=listNode;
listNode.pre=t;
t.next=listNode;
size++;
}
public void deleteAtIndex(int index) {
if(index<0||index>=size)return;
ListNode t=head;
if(size==0){
head=head.next;
return;
}
for (int i = 0; i < index; i++) {
t=t.next;
}
t.next.next.pre=t;
t.next=t.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);
*/