203.移除链表元素
注意几个细节
1.首先第一个while循环不能写成while嵌套if的写法比如说:
while(head!=null){
if(head.val == val){
head = head.next;
}
}
因为如果我们不是要遍历结束,我们是只要保证头节点不是空指针并且头节点的值不为val就ok了
2.cur是指针 注意不要和head头节点搞混
3.我经常犯的错误 误把cur.next 与cur.next.val 混为一谈
不使用虚拟节点:
class Solution {
public ListNode removeElements(ListNode head, int val) {
while(head!= null&&head.val ==val){
head = head.next;
}
ListNode cur = head;
while(cur!=null&&cur.next!=null){
if(cur.next.val == val){
cur.next = cur.next.next;
}else{
cur = cur.next;
}
}
return head;
}
}
使用虚拟节点
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode dummy = new ListNode();
dummy.next = head;
ListNode cur = dummy;
while(cur.next !=null){
if(cur.next.val == val){
cur.next = cur.next.next;
}else{
cur = cur.next;
}
}
return dummy.next;
}
}
707.设计链表
该题暂时没有时间解析
class MyLinkedList {
int size = 0;
ListNode head;//虚拟头节点
class ListNode{
int val;
ListNode next;
ListNode(){}
ListNode(int val){
this.val = val;
}
}
public MyLinkedList() {
head = new ListNode(0);
}
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;
}
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;
}
size++;
ListNode cur = head;
for(int i = 0;i <index ;i++ ){
cur = cur.next;
}
ListNode node = new ListNode(val);
node.next = cur.next;
cur.next = node;
}
public void deleteAtIndex(int index) {
if(index<0||index>=size){
return;
}
size--;
ListNode cur = head;
for(int i = 0;i <index ;i++ ){
cur = cur.next;
}
cur.next = cur.next.next;
}
}
206.反转链表
双指针版
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;
}
}
递归版
class Solution {
public ListNode reverseList(ListNode head) {
return reverse(null,head);
}
private ListNode reverse(ListNode pre,ListNode cur){
if(cur == null){
return pre;
}
ListNode temp = cur.next;
cur.next = pre;
return reverse(cur,temp);
}
}