题解 | #反转链表#
反转链表
http://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
/**
- struct ListNode {
- int val;
- struct ListNode *next;
- };
- C语言声明定义全局变量请加上static,防止重复定义 */
/** *
-
@param pHead ListNode类
-
@return ListNode类 / struct ListNode ReverseList(struct ListNode* pHead ) { struct ListNode *pre=NULL,*temp=NULL; struct ListNode *cur=pHead; while(cur!=NULL) {
temp=cur->next;//保存当前结点的下一个结点的值,防止链表断开时找不到下一个结点 cur->next=pre;//让cur指向pre pre=cur;//pre向前移动一步到cur的位置 cur=temp;//cur向前移动一步到cur的下一个结点的位置
} return pre;//循环结束时pre指向链表反转后头结点的位置
}