##在线笔经##
前天消消乐笔试,题目是接收输入的带空格的n个Int类型的数字,生成链表,再进行排序。
输入如下代码即可,后台自动处理链表的生成,再使用insertionSortList函数进行排序。
如果排序方法不是该名称,会报错提示。链表结点的声明不是ListNode,也会报错。node的两个字段也必须是next和val,别的不行。。。
public static ListNode insertionSortList(ListNode head){
if(head == null || head.next == null)
return head;
ListNode p1 = head;
ListNode p2 = head.next;
while(p1.next != null){
while(p2 != null){
if (p2.val < p1.val) {
int tmp = p2.val;
p2.val = p1.val;
p1.val = tmp;
}
p2 = p2.next;
}
p1 = p1.next;
p2 = p1.next;
}
return head;
}
如果自己写了接收字符和生成链表的方法,可以用自己的Main函数。
public class Solution {
public static ListNode insertionSortList(ListNode head){
if(head == null || head.next == null)
return head;
ListNode p1 = head;
ListNode p2 = head.next;
while(p1.next != null){
while(p2 != null){
if (p2.val < p1.val) {
int tmp = p2.val;
p2.val = p1.val;
p1.val = tmp;
}
p2 = p2.next;
}
p1 = p1.next;
p2 = p1.next;
}
return head;
}
public static void printList(ListNode head){
while(head!=null){
System.out.print(head.val+" ");
head = head.next;
}
}
public void Main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<Integer> array = new ArrayList<Integer>();
String s = sc.nextLine();
String[] s1 = s.split(" ");
for (int i = 0; i < s1.length; i++) {
array.add(Integer.valueOf(s1[i]));
}
ListNode head = new ListNode(s1.length);
ListNode p = head;
for (int i = 0; i < array.size(); i++) {
ListNode node = new ListNode(array.size());
node.val = array.get(i);
node.next = null;
p.next = node;
p = node;
}
insertionSortList(head.next);
printList(head.next);
}
}
也可以正常编译运行通过!
再者,网上搜到一种方法,是摘节点再插入,比较麻烦(也是一种思想),如下:
public class SolutionForInsertNode {
Node myHead;
public Node insertionSortList(Node head) {
Node cursor = head;
myHead = head;
while (cursor != null) {
Node temp = cursor.next;
if (temp != null && temp.value < cursor.value) { // 如果该结点的后一个结点比该节点小
cutLink(cursor); // 将后一个结点从链表中取出
insertNode(temp, head); // 将后一个结点插入到适合的位置
} else {
cursor = cursor.next;
}
}
return myHead;
}
public void cutLink(Node one) {
Node two = one.next;
Node three = two.next;
one.next = three;
two.next = null;
}
public void insertNode(Node node, Node head) {
Node temp = myHead;
Node pre = null;
while (node.value > temp.value) {
pre = temp;
temp = temp.next;
}
node.next = temp;
if (pre != null) {
pre.next = node;
} else {
myHead = node;
}
}
}
!!!
在线编程和本地编程,差别真大!!!
!!!
注意事项:
- 题目有多个类型的(有的笔试会有很多题目类型,先做编程或者先做问答或者先做代码填空,需要根据情况选择顺序。)
- 自己写主函数要写成Main