描述
删除给出链表中的重复元素(链表中元素从小到大有序),使链表中的所有元素都只出现一次
题目求解:利用虚拟头节点,减少处理过程的复杂度;注意空节点是没有next节点的
public class Solution {
/**
*
* @param head ListNode类
* @param x int整型
* @return ListNode类
*/
public ListNode partition (ListNode head, int x) {
// write code here
if(head==null) return null;
ListNode tail=null;
ListNode temp=head;
int len=1;
while(temp.next!=null)
{
temp=temp.next;
len++;
}
tail=temp;
if(head==temp) return head;
temp=new ListNode(Integer.MIN_VALUE);
temp.next=head;
ListNode head_temp=temp;
ListNode temp_pre=temp;
for(int i=0;i<=len;i++)
{
if(temp.val>=x)
{
temp_pre.next=temp.next;
tail.next=temp;
tail=temp;
temp=temp.next;
tail.next=null;
continue;
}
temp_pre=temp;
temp=temp.next;
}
return head_temp.next;
}
}