示例:web
输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5svg
这个题考察了对单向链表的遍历,以及对其next和val属性的理解,加以判断就能够作出来。code
/** * 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。xml
示例:rem
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULLit
直接对输入的链表进行头插不就反过来了吗?io
/** * 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; } }