删除链表中等于给定值 val 的所有节点。
示例:
输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5
这个题考察了对单向链表的遍历,以及对其next和val属性的理解,加以判断就可以做出来。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode header = new ListNode(-1);
header.next = head;
ListNode cur = header;
while(cur.next != null){
if(cur.next.val == val){
cur.next = cur.next.next;
}else{
cur = cur.next;
}
}
return header.next;
}
}
我们事先创建好一个链表并将第一个元素的值设为-1,便于循环遍历,如果传入空链表也能够进行处理,创建两个标记,一个用来最后的输出也就是header,一个是cur用来进行数据操作,找到相等的值就将这个结点的next变成下下个结点的next,不是就直接next。
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
直接对输入的链表进行头插不就反过来了吗?
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode res = null;
ListNode cur = head;
while(cur != null){
ListNode next = cur.next;
cur.next = res;
res = cur;
cur = next;
}
return res;
}
}