203.移除链表元素
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;
}
ListNode curr = head;
while(curr!=null && curr.next !=null) {
if(curr.next.val == val){
curr.next = curr.next.next;
} else {
curr = curr.next;
}
}
return head;
}
}
707.设计链表
class ListNode {
int val;
ListNode next;
public ListNode () {
}
public ListNode ( int val) {
this.val = val;
}
}
class MyLinkedList {
ListNode newNode;
public MyLinkedList() {
newNode = new ListNode(0);
}
public int get(int index) {
ListNode cur = newNode.next;
int count = 0;
while (cur != null) {
if (count == index) {
return cur.val;
}
count ++;
cur = cur.next;
}
return -1;
}
public void addAtHead(int val) {
ListNode newHead = new ListNode(val);
ListNode tem = new ListNode();
tem = newNode.next;
newNode.next = newHead;
newHead.next = tem;
}
public void addAtTail(int val) {
ListNode newTail = new ListNode(val);
ListNode cur = newNode.next;
ListNode pre = newNode;
while(cur != null){
cur = cur.next;
pre = pre.next;
}
pre.next = newTail;
}
public void addAtIndex(int index, int val) {
ListNode addNode = new ListNode(val);
ListNode cur = newNode.next;
ListNode pre = newNode;
int count = 0;
while( cur != null) {
if (count == index) {
pre.next = addNode;
addNode.next = cur;
}
count ++;
cur = cur.next;
pre = pre.next;
}
if (count == index) {
pre.next = addNode;
}
}
public void deleteAtIndex(int index) {
int count = 0;
ListNode cur = newNode.next;
ListNode pre = newNode;
while(cur != null) {
if (count == index) {
pre.next = cur.next;
return;
}
count ++;
cur = cur.next;
pre = pre.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 || head.next == null) return head;
ListNode cur = head.next;
ListNode pre = head;
ListNode tem = new ListNode();
while ( cur != null) {
tem = cur.next;//下次cur移动到这里了,pre 移动到cur这里
cur.next = pre;
if (pre == head) pre.next = null;
//更新节点
pre = cur;
cur = tem;
}
head = pre;
return head;
}
}