您的位置:首页 > 职场人生

链表相关面试题

2017-10-03 13:29 288 查看
使用插入排序对链表进行排序(Sort a linked list using insertion sort.):

public  ListNode insertionSortList(ListNode head) {

if (head == null) {
return head;
}

ListNode toInsert = head;
ListNode newHead = null;

while (toInsert != null) {

ListNode cur = newHead;
ListNode next = toInsert.next;

// 判断头部
if (cur == null||toInsert.val <= newHead.val) {

toInsert.next = cur;
newHead = toInsert;

} else {

while (cur.next != null) {

if (cur.val <= toInsert.val && toInsert.val <= cur.next.val) {

toInsert.next = cur.next;
cur.next = toInsert;
break;
}
cur =cur.next;

}
//如果待插入的数是最大的,就把它放在后面
if (cur.next == null) {
cur.next = toInsert;
toInsert.next = null;
}

}

toInsert = next;
}

return newHead;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息