203.移除链表元素
题目链接:203.移除链表元素
思路:1.直接在原链表上进行删除操作、2.设置虚拟头结点进行删除操作
解法1:直接操作
首先采用while循环判断头结点不为空且头结点处值为输入值,头结点指针后移一位;
定义新指针cur指向头结点,while循环判断新指针cur不为null且cur指针指向的下一位不为null,当cur.next指向的值为输入值时,cur.next.next的地址赋值给cur.next实现删除操作。否则cur向后移动一位。
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode cur = head;
while(head!=null&&head.val == val){
head = head.next;
}
while(cur!=null&&cur.next!=null){
if(cur.next.val == val){
cur.next = cur.next.next;
}else{
cur = cur.next;
}
}
return head;
}
}
解法2:设置虚拟头节点
class Solution {
public ListNode removeElements(ListNode head, int val) {
if (head == null) {
return head;
}
ListNode dummy = new ListNode(-1, head);
ListNode pre = dummy;
ListNode cur = head;
while (cur != null) {
if (cur.val == val) {
pre.next = cur.next;
} else {
pre = cur;
}
cur = cur.next;
}
return dummy.next;
}
}
707.设计链表
题目链接:707.设计链表
思路:1.直接在原链表上进行删除操作、2.设置虚拟头结点进行删除操作
解法1:直接操作
解法2:设置虚拟头结点
class ListNode {
int val;
ListNode next;
ListNode(){}
ListNode(int val) {
this.val=val;
}
}
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 cur = head;
for (int i = 0; i <= index; i++) {
cur = cur.next;
}
return cur.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 pre = head;
for (int i = 0; i < index; i++) {
pre = pre.next;
}
ListNode add = new ListNode(val);
add.next = pre.next;
pre.next = add;
}
public void deleteAtIndex(int index) {
if (index < 0 || index >= size) {
return;
}
size--;
if (index == 0) {
head = head.next;
return;
}
ListNode pre = head;
for (int i = 0; i < index ; i++) {
pre = pre.next;
}
pre.next = pre.next.next;
}
}
206.反转链表
题目链接:206.反转链表
思路:1.双指针法、2.递归法
解法1:双指针法
定义当前结点前一个结点指针pre,当前结点指针cur和中转指针temp用于保存结点。
temp保存cur.next结点,通过cur.next = pre改变cur.next的指向,cur指针向后移动一位,pre指针也向后移动一位。
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode cur = head;
ListNode temp;
while(cur != null){
temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}
}
解法2:递归法
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 = null;
temp = cur.next;
cur.next = pre;
return reverse(cur, temp);
}
}