1 package struct;
2
3 /**
4 * Created by moi on 2017/10/18.
5 */
6 public class LinkList {
7 /**
8 * Definition for singly-linked list.
9 */
10 public class ListNode {
11 int val;
12 ListNode next;
13
14 ListNode(int x) {
15 val = x;
16 }
17 }
18
19
20 /**
21 * 移除链表相同值
22 * @param head a ListNode
23 * @param val an integer
24 * @return a ListNode
25 */
26 public ListNode removeElements(ListNode head, int val) {
27 if (head == null) {
28 return null;
29 }
30 if (head.next == null) {
31 if (head.val == val) {
32 return null;
33 } else {
34 return head;
35 }
36 }
37 ListNode current = head;
38 ListNode pre = null;
39 boolean flag = false;
40 while (current.next != null) {
41 if (current.val == val) {
42 if (pre != null) {
43 pre.next = current.next;
44 }
45 current = current.next;
46 } else {
47 pre = current;
48 if (flag == false) {
49 head = current;
50 flag = true;
51 }
52 current = current.next;
53 }
54 }
55 if (pre == null) {
56 return null;
57 }
58 if (current.next == null) {
59 if (current.val == val) {
60 pre.next = null;
61 }
62 }
63 return head;
64
65 }
66
67 }