1、在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点保留一个,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
private static ListNode fun2(ListNode head) {
ListNode res = new ListNode(0);
res.next = head;
ListNode temp = head;
ListNode res2 = res;
while (temp!=null){
if(temp.next!=null && temp.val == temp.next.val){
while (temp.next!=null && temp.val == temp.next.val){
temp =temp.next;
res = res.next;
}
temp = temp.next;
res.next = temp;
}else{
temp = temp.next;
res = res.next;
}
}
return res2.next;
}
2、输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
public class test012 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
String str = sc.nextLine();
char[] chars = str.toCharArray();
ArrayList<String> list = new ArrayList<>();
fun(chars, 0, list);
for(int i=0; i<list.size(); i++){
System.out.println(list.get(i));
}
}
}
private static void fun(char[] chars, int begin, ArrayList<String> list) {
if(chars.length == 0 || chars == null || begin<0 || begin>chars.length){
return;
}
if(begin == chars.length-1){
list.add(String.valueOf(chars));
}else{
for(int i=begin; i<chars.length; i++){
swap(chars, begin, i);
fun(chars, begin+1, list);
swap(chars, begin, i);
}
}
}
private static void swap(char[] chars, int i, int j) {
char temp = chars[i];
chars[i] = chars[j];
chars[j] = temp;
}