题解 | #单链表的排序#
单链表的排序
http://www.nowcoder.com/practice/f23604257af94d939848729b1a5cda08
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*
* C语言声明定义全局变量请加上static,防止重复定义
*/
/**
*
* @param head ListNode类 the head node
* @return ListNode类
*/
struct ListNode* sortInList(struct ListNode* head ) {
// write code here
//冒泡排序
struct ListNode *p1,*p2;
p1 = p2 = head;
while(p1 != NULL)
{
p2 = p1->next;
while(p2 != NULL)
{
if(p2->val<p1->val)
{
int tmp;
tmp = p1->val;
p1->val = p2->val;
p2->val = tmp;
}
p2 = p2->next;
}
p1 = p1->next;
}
return head;
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*
* C语言声明定义全局变量请加上static,防止重复定义
*/
/**
*
* @param head ListNode类 the head node
* @return ListNode类
*/
struct ListNode* sortInList(struct ListNode* head ) {
// write code here
//冒泡排序
struct ListNode *p1,*p2;
p1 = p2 = head;
while(p1 != NULL)
{
p2 = p1->next;
while(p2 != NULL)
{
if(p2->val<p1->val)
{
int tmp;
tmp = p1->val;
p1->val = p2->val;
p2->val = tmp;
}
p2 = p2->next;
}
p1 = p1->next;
}
return head;
}