目录
- 203. 移除链表元素
- 707. 设计链表
- 206. 反转链表
- 双指针法
- 递归法
203. 移除链表元素
文档讲解:https://programmercarl.com/0203.%E7%A7%BB%E9%99%A4%E9%93%BE%E8%A1%A8%E5%85%83%E7%B4%A0.html
视频讲解:https://www.bilibili.com/video/BV18B4y1s7R9/
状态:AC
参考代码:
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
dummyHead = ListNode()
dummyHead.next = head
cur = dummyHead
while cur.next != None:
if cur.next.val == val:
cur.next = cur.next.next
else:
cur = cur.next
head = dummyHead.next
return head
707. 设计链表
文档讲解:https://programmercarl.com/0707.%E8%AE%BE%E8%AE%A1%E9%93%BE%E8%A1%A8.html
视频讲解:https://www.bilibili.com/video/BV1FU4y1X7WD/?vd_source=165e4607770e3b9e1cb99113773370c5
状态:AC
此题设计链表的各种操作,见题解,特别是双链表法。
class Node:
def __init__(self, _val):
self.val = _val
self.prev = None
self.next = None
class MyLinkedList:
def __init__(self):
self.he = Node(-1)
self.ta = Node(-1)
self.he.next = self.ta
self.ta.prev = self.he
self.sz = 0
def get(self, index):
node = self.getNode(index)
return node.val if node else -1
def addAtHead(self, val):
node = Node(val)
node.next = self.he.next
node.prev = self.he
self.he.next.prev = node
self.he.next = node
self.sz += 1
def addAtTail(self, val):
node = Node(val)
node.prev = self.ta.prev
node.next = self.ta
self.ta.prev.next = node
self.ta.prev = node
self.sz += 1
def addAtIndex(self, index, val):
if index > self.sz:
return
if index <= 0:
self.addAtHead(val)
elif index == self.sz:
self.addAtTail(val)
else:
node, cur = Node(val), self.getNode(index)
node.next = cur
node.prev = cur.prev
cur.prev.next = node
cur.prev = node
self.sz += 1
def deleteAtIndex(self, index):
node = self.getNode(index)
if node:
node.prev.next = node.next
node.next.prev = node.prev
self.sz -= 1
def getNode(self, index):
isLeft = index < self.sz / 2
if not isLeft:
index = self.sz - index - 1
cur = self.he.next if isLeft else self.ta.prev
while cur != self.he and cur != self.ta:
if index == 0:
return cur
index -= 1
cur = cur.next if isLeft else cur.prev
return None
206. 反转链表
文档讲解:https://programmercarl.com/0206.%E7%BF%BB%E8%BD%AC%E9%93%BE%E8%A1%A8.html
视频讲解:https://www.bilibili.com/video/BV1nB4y1i7eL/
状态:AC
双指针法
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* temp; // 保存cur的下一个节点
ListNode* cur = head;
ListNode* pre = NULL;
while(cur) {
temp = cur->next; // 保存一下 cur的下一个节点,因为接下来要改变cur->next
cur->next = pre; // 翻转操作
// 更新pre 和 cur指针
pre = cur;
cur = temp;
}
return pre;
}
};
递归法
class Solution {
public:
ListNode* reverse(ListNode* pre,ListNode* cur){
if(cur == NULL) return pre;
ListNode* temp = cur->next;
cur->next = pre;
// 可以和双指针法的代码进行对比,如下递归的写法,其实就是做了这两步
// pre = cur;
// cur = temp;
return reverse(cur,temp);
}
ListNode* reverseList(ListNode* head) {
// 和双指针法初始化是一样的逻辑
// ListNode* cur = head;
// ListNode* pre = NULL;
return reverse(NULL, head);
}
};