LeetCode 203.移除链表元素
题目链接🔗:LeetCode 203.移除链表元素
思路
代码实现
class ListNode{
int val;
ListNode next;
public ListNode() {
}
public ListNode(int val) {
this.val = val;
}
public ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
public ListNode removeElements(ListNode head, int val){
while(head!=null && head.val==val){
head = head.next;
}
ListNode p = head;
while(p != null){
while(p.next != null && p.next.val == val){
p.next = p.next.next;
}
p = p.next;
}
return head;
}
LeetCode 707.设计链表
题目链接🔗:LeetCode 707.设计链表
思路
设置一个虚拟头结点在进行操作
删除链表结点:
添加链表结点:
代码实现
class ListNode{
int val;
ListNode next;
public ListNode() {
}
public ListNode(int val) {
this.val = val;
}
public ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
class MyLinkedList {
//size存储链表元素的个数
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 p = head;
for (int i = 0; i <= index; i++) {
p = p.next;
}
return p.val;
}
public void addAtHead(int val) {
ListNode listNode = new ListNode(val);
listNode.next = head.next;
head.next = listNode;
size++;
}
public void addAtTail(int val) {
ListNode listNode = new ListNode(val);
ListNode p = head;
while(p != null){
if (p.next == null){
p.next = listNode;
break;
}
p = p.next;
}
size++;
}
public void addAtIndex(int index, int val) {
if (index < 0 || index > size){
return;
}
ListNode p = head;
ListNode listNode = new ListNode(val);
for (int i = 0; i < index; i++) {
p = p.next;
}
listNode.next = p.next;
p.next = listNode;
size++;
}
public void deleteAtIndex(int index) {
if (index < 0 || index > size - 1){
return;
}
ListNode p = head;
for (int i = 0; i < index; i++) {
p = p.next;
}
p.next = p.next.next;
size--;
}
}
LeetCode 206.反转链表
题目链接🔗:LeetCode 206.反转链表
思路
定义一个pre结点指向,pre的下一个结点指向head
定义一个cur结点指向head
定义一个temp结点指向head
循环内首先让temp结点移动到下一个结点
让cur的下一个结点指向pre
pre移动到下一个结点
cur移动到下一个结点
循环完成让head的下一个结点指向null,返回pre即为反转后的链表
(动画应该是先移动pre,在移动cur)
代码实现
class ListNode{
int val;
ListNode next;
public ListNode() {
}
public ListNode(int val) {
this.val = val;
}
public ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
public ListNode reverseList(ListNode head) {
if (head == null){
return null;
}
ListNode pre = new ListNode(0,head);
ListNode cur = head;
ListNode temp = head;
while (temp != null){
temp = temp.next;
cur.next = pre;
pre = cur;
cur = temp;
}
head.next = null;
return pre;
}