This problem is quite easy. Use a current node and a node just before it to traverse this linked list, compare the value of current node with preNode, if same, delete current node, otherwise, move both to next one.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (head == null || head.next == null) return head;
ListNode preNode = head;
int value = preNode.val;
ListNode currentNode = head.next;
while(currentNode !=null ){
if(value == currentNode.val){
preNode.next = currentNode.next;
currentNode.next = null;
currentNode = preNode.next;
}
else{
preNode = preNode.next;
currentNode = currentNode.next;
value = preNode.val;
}
}
return head;
}
}
Hello, welcome to Yizhe's Blog. I am Yizhe Liu, graduated from University of Arizona, with Master degree, major in Electrical and Computer Engineering. Actually, I am software guy. In my blog, many posts are about the Leetcode questions. I will post my ideas and implementations, which are accepted by Leetcode. If you have different opinions, please leave comment. I am happy to discuss with you. So lets start rocking them!!!
Sunday, June 1, 2014
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment