203.移除链表元素
/**
* 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) {
while(head!=null&&head.val==val){
head=head.next;
}
if(head==null){
return head;
}
ListNode pre = head;
ListNode cur = head.next;
while (cur!=null){
if(cur.val == val){
pre.next = cur.next;
}else {
pre = cur;
}
cur = cur.next;
}
return head;
}
}
707.设计链表
static class MyLinkedList {
int size;
//虚拟头节点
ListNode head;
//初始化链表
public MyLinkedList() {
size = 0;
head = new ListNode(0);
}
//获取链表中第index节点的值,如果索引无效,返回-1
public int get(int index) {
if(index<0 || index >=size){
return -1;
}
ListNode currentNode = head;
for (int i = 0; i <= index; i++) {
currentNode = currentNode.next;
}
return currentNode.val;
}
//在链表第一个元素之前添加一个值为val的节点,成为头节点
public void addAtHead(int val) {
addAtIndex(0,val);
}
//将值为val的节点追加到链表的最后一个元素
public void addAtTail(int val) {
addAtIndex(size,val);
}
//在链表中第index的位置添加值为val的节点,需要判断index的值
public void addAtIndex(int index, int val) {
if(index>size){
return;
}
if(index<0){
index=0;
}
size++;
ListNode pred = head;
for (int i = 0; i <index; i++) {
pred=pred.next;
}
ListNode toAdd= new ListNode(val);
toAdd.next = pred.next;
pred.next = toAdd;
}
//删除索引为index的节点
public void deleteAtIndex(int index) {
if(index<0 || index >=size){
return;
}
size--;
if(index == 0){
head= head.next;
return;
}
ListNode pred = head;
for (int i = 0; i <index; i++) {
pred=pred.next;
}
pred.next=pred.next.next;
}
}
206.反转链表
只需要改变next的指针就可以实现链表反转
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode cur = head;
ListNode temp = null;
while(cur!=null){
temp = cur.next;
cur.next = pre;
pre = cur;
cur=temp;
}
return pre;
}
}