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) {
ListNode dummyHead = new ListNode();
dummyHead.next=head;
ListNode curr = dummyHead;
while(curr.next != null){
if(curr.next.val == val){
curr.next = curr.next.next;
}else{
curr=curr.next;
}
}
return dummyHead.next;
}
}
707.设计链表
class ListNode {
int val;
ListNode next;
public ListNode(int val) {
this.val = val;
}
public ListNode() {
}
}
class MyLinkedList {
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 curr = head;
for (int i = 0; i <= index ; i++) {
curr = curr.next;
}
return curr.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;
}
if(index<0){
index = 0;
}
size++;
ListNode curr = head;
for (int i = 0; i < index; i++) {
curr = curr.next;
}
ListNode newNode = new ListNode(val);
newNode.next = curr.next;
curr.next = newNode;
}
public void deleteAtIndex(int index) {
if (index < 0 || index >= size) {
return;
}
size--;
if(index == 0){
head = head.next;
return;
}
ListNode curr = head;
for (int i = 0; i < index ; i++) {
curr =curr.next;
}
curr.next=curr.next.next;
}
}
/**
* 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.反转链表
/**
* 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 reverseList(ListNode head) {
if(head == null){
return null;
}
if(head.next == null){
return head;
}
ListNode pre = null, cur = head,tmp;
while(cur != null){
tmp = cur.next;
cur.next = pre;
pre = cur;
cur = tmp;
}
return pre;
}
}
标签:head,ListNode,val,int,随想录,next,链表,移除,curr
From: https://www.cnblogs.com/Chain-Tian/p/16911881.html