代码随想录第三天 | 203.移除链表元素 707.设计链表 206.反转链表
LeetCode:203. 移除链表元素 - 力扣(LeetCode)
思路:移除链表只是跳过需要移除的链表即可,即cur=cur.next
有关虚拟头结点:
首先要建立一个结点作为虚拟头结点,也就是在head前加一个,然后因为虚拟头和一会要遍历的指针指向的内容不能变,所以用cur代替head,pre也就是虚拟头,当cur.val符合时,将cur.next赋给虚拟头pre后边。
链表头结点不能为空,空就是链表到头了。
public ListNode removeElements(ListNode head, int val) {
//创建虚拟头和指针
ListNode node = new ListNode(-1, head);
ListNode pre = node;
//代替指针
ListNode cur = head;
while (cur != null) {
if (cur.val == val) {
pre.next = cur.next;
} else {
pre = cur;
}
cur = cur.next;
}
return node.next;
}
LeetCode:707. 设计链表 - 力扣(LeetCode)
思路:几乎没有,太乱了
反思:
//for循环模拟的是链表从开始到结束遍历的过程
//链表插入总是先写add.next=pre.next;在写pre.next = add;
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 pred = head;
for(int i = 0;i < index; i++){
pred=pred.next;
}
ListNode toAdd = new ListNode(val);
toAdd.next = pred.next;
pred.next = toAdd;
}
public void deleteAtIndex(int index) {
if(index < 0|| index >= size){
return;
}
size--;
if(index == 0){
head = head.next;
return;
}
ListNode pred = head;
for(int i=0; i < index ; i++){
pred=pred.next;
}
pred.next=pred.next.next;
}
}
/**
* Your MyLinkedList object will be instantiated and called as such:
* MyLinkedList obj = new MyLinkedList();
* int param_1 = obj.get(index);
* obj.addAtHead(val);
* obj.addAtTail(val);
* obj.addAtIndex(index,val);
* obj.deleteAtIndex(index);
*/
//leetcode submit region end(Prohibit modification and deletion)
}
LeetCode:206. 反转链表 - 力扣(LeetCode)
思路,画图后会清晰一点,将链表就是改指针,反转就是将头指向尾,除了head和null外就是将其他的反转过来,pre=cur.next反转为cur.next=pre不就改掉了,由于改指针cur.next找不到
,所以要用一个临时值来存储,temp=cur.next;pre=cur是往前走一下cur=temp;是继续存储cur;
public ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode cur = head;
ListNode temp = cur;
while(cur!=null)
{
temp = cur.next;
cur.next=pre;
pre = cur;
cur=temp;
}
return pre;
}