Write a nonrecursive procedure to reverse a singly linked list in O(N) time using constant extra space.
题目在PTA上,是学习了DS后自己写出来的第一个算法,有点粗浅。
头插法实现逆转链表
List Reverse(List L)
{
List current;
current=L->Next;
while(current!=NULL&¤t->Next!=NULL)
{
current->Next=L->Next;
L->Next=current->Next;
}
return L;
}
头插法:选定一个标定,每次把标定之后的值插入到链表最前面,直到标定后是NULL。
这个方法可以直接在原本的链表上操作,不用另外开辟空间,实在是方便又机智的好方法。