关于链表这种数据结构相信大家都十分熟悉,谈起来都能如数家珍,但是如果让你写链表相关的算法题的时候就很容易出错,处理不好链表循环中的引用的问题。这个时候需要将每个节点当作一个对象来看待,这个对象中有个next 引用,指向的下一个节点。同时对象中保存了当前节点的值,一旦修改了next引用,那么这个节点的下一个节点就指向了其他的节点,也就意味着这个链表发生了变化。
删除链表中的元素
在处理头节点和其他节点的时候需要做下区别,这里使用了一个虚拟的头节点
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode dummy = new ListNode(-1, head);//定义一个虚拟的头节点
ListNode prev = dummy;
ListNode current = head;
while(current != null) {
if(current.val == val) {
prev.next = current.next;
} else {
prev = current;
}
current = current.next;
}
return dummy.next;
}
}
设计一个链表
设计一个链表,包含一些简单的操作。
class MyLinkedList {
ListNode head;
class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
public MyLinkedList() {
}
public int get(int index) {
ListNode current = head;
int pos = index;
int result = -1;
while(current != null && pos >= 0) {
if(pos == 0) {
result = current.val;
break;
}
current = current.next;
pos --;
}
return result;
}
public void addAtHead(int val) {
ListNode newHead = new ListNode(val, this.head);
this.head = newHead;
}
public void addAtTail(int val) {
if (head == null) {
addAtHead(val);
return;
}
ListNode current = head;
while(current.next != null) {
current = current.next;
}
current.next = new ListNode(val, null);
}
public void addAtIndex(int index, int val) {
int pos = index - 1;
ListNode current = head;
if(index <= 0) {
head = new ListNode(val, head);
}
while(current != null && pos >= 0) {
if(pos == 0) {
current.next = new ListNode(val, current.next);
break;
}
current = current.next;
pos --;
}
}
public void deleteAtIndex(int index) {
ListNode current = head;
int pos = index - 1;
if(index == 0) {
this.head = head.next;
}
while(current != null && current.next != null && pos >= 0) {
if(pos == 0) {
current.next = current.next.next;
break;
}
current = current.next;
pos --;
}
}
@Override
public String toString() {
ListNode current = head;
StringBuilder sb = new StringBuilder();
while (current != null) {
sb.append(current.val);
sb.append(",");
current = current.next;
}
return sb.toString();
}
}
反转链表
经典的链表相关的题目,之前也是做过很多遍,再做的时候依然修修改改花了些时间
class Solution {
public ListNode reverseList(ListNode head) {
ListNode current = head;
ListNode prev = null;
// ListNode result = head;
while(current != null) {
ListNode next = current.next;
current.next = prev;
prev = current;
current = next;
}
return prev;
}
}