代码随想录算法训练营第三天|LeetCode203,707,206
203. 移除链表的元素
本题比较基础,主要是考虑虚拟头结点的使用。
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode dummy = new ListNode();
dummy.next = head;
ListNode flag = new ListNode();
flag = dummy;
//如何判断链表的遍历结束?
while(flag.next != null){
if(flag.next.val == val){
flag.next = flag.next.next;
}else {
flag = flag.next;
}
}
return dummy.next;
}
}
707.设计链表
主要是考察链表的一些基本操作的实现思路,有单、双链表两种形式,注意部分判断条件的设计
class MyLinkedList{
//链表的长度
int size;
//虚拟头结点
LinkNode head;
//构造函数
public MyLinkedList() {
size = 0;
head = new LinkNode();
}
public int get(int index) {
if (index<0||index >= this.size){
return -1;
}
LinkNode flag = head;
//这里是<=index
for(int i = 0;i<= index;i++){
flag = flag.next;
}
return flag.val;
}
public void addAtHead(int val) {
LinkNode newNode = new LinkNode(val);
newNode.next = head.next;
head.next = newNode;
size++;
//System.out.println(head.next.val);
//test();
}
public void addAtTail(int val) {
LinkNode tailNode = head;
for (int i = 0; i<size;i++){
tailNode = tailNode.next;
}
LinkNode node = new LinkNode(val);
tailNode.next = node;
size++;
//test();
// System.out.println(head.next.val);
// System.out.println(tailNode.val);
// System.out.println(tailNode.next.val);
}
public void addAtIndex(int index, int val) {
if (index <= 0 ){
addAtHead(val);
} else if (index == size) {
addAtTail(val);
}else if(index > size){
return;
}else {
LinkNode tmp = head;
for(int i = 0;i<= index-1;i++){
tmp = tmp.next;
}
LinkNode newNode = new LinkNode(val);
newNode.next = tmp.next;
tmp.next = newNode;
size++;
}
//test();
}
public void deleteAtIndex(int index) {
if (0<=index && index<size){
LinkNode bef = head;
for(int i = 0;i<= index - 1;i++){
bef = bef.next;
}
bef.next = bef.next.next;
}else{
return;
}
size--;
System.out.println("当前执行的为删除操作");
//test();
}
public void test(){
System.out.println("当前链表为:");
LinkNode node = head;
for (int i = 0; i < size;i++ ){
node = node.next;
System.out.print(node.val+" ");
}
System.out.println(" ");
}
}
206.反转链表
最开始的思路是直接新定义一个链表来实现对就链表的反转,但造成了内存空间的浪费,考虑直接在原链表上反转指针。
public ListNode reverseList(ListNode head) {
ListNode tmp ;
ListNode cur = head;
ListNode pre = null;
while (cur != null){
tmp = cur.next;
cur.next = pre;
pre = cur;
cur = tmp;
}
return pre;
}
可以进一步考虑递归的方式,先明确递归退出条件
public ListNode reverse(ListNode pre, ListNode cur){
if (cur == null) return pre;
ListNode tmp = cur.next;
cur.next = pre;
return reverse(cur,tmp);
}
public ListNode reverseList(ListNode head){
return reverse(null,head);
}
```