leetcode 反转链表&移除链表元素
leetcode 反转链表&移除链表元素
反转链表
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
示例 1:
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
作者:力扣 (LeetCode)
链接:https://leetcode-cn.com/leetbook/read/linked-list/f58sg/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
迭代法
思路:用指针指向头节点,然后往后遍历,先将头节点后的节点放到头节点前,成为新的头节点,在将指针后的一个节点放到头,如此遍历到原来的头节点变成尾节点,head.next=null
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if(head==null){
return null;
}
ListNode ret = head;
while(head.next!=null){
ListNode temp = head.next;
head.next=head.next.next;
temp.next=ret;
ret=temp;
}
return ret;
}
}
移除链表元素
递归
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
//这是我写的
public ListNode removeElements(ListNode head, int val) {
if(head==null){
return null;
}
else if(head.val==val){
return removeElements(head.next,val);
}
else{
head.next=removeElements(head.next,val);
}
return head;
}
//这是官方题截
public ListNode removeElements(ListNode head, int val) {
if (head == null) {
return head;
}
head.next = removeElements(head.next, val);
return head.val == val ? head.next : head;
}
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/remove-linked-list-elements/solution/yi-chu-lian-biao-yuan-su-by-leetcode-sol-654m/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
}
迭代
思路:给链表加上哨兵节点(哨兵节点真的好用),然后遍历链表,如果当前节点的下一个的值符合题目,跳过该节点,否则不跳过
public ListNode removeElements(ListNode head, int val) {
ListNode ret = new ListNode(-1,head);
ListNode temp = ret;
while(temp.next!=null){
if(temp.next.val==val){
temp.next=temp.next.next;
}
else{
temp=temp.next;
}
}
return ret.next;
}

浙公网安备 33010602011771号