牛客网:NC78 反转链表
尝试了几种不同思路:
目前最优的方案:
基本思想是使用3个临时变量来转换链表顺序。
next是转换后的next节点;cur是当前操作转换的节点;prev是下一个当前节点。
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
*
* @param pHead ListNode类
* @return ListNode类
*/
struct ListNode* ReverseList(struct ListNode* pHead ) {
// write code here
struct ListNode* cur = NULL;
struct ListNode* prev = NULL;
struct ListNode* next = NULL;
if(NULL == pHead)
{
//printf("input error\n");
return NULL;
}
prev = pHead;
while(NULL != prev)
{
next = cur;
cur = prev;
prev = prev->next;
cur->next = next;
}
pHead = cur;
return pHead;
}
次优方案:
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
*
* @param pHead ListNode类
* @return ListNode类
*/
struct ListNode* ReverseList(struct ListNode* pHead ) {
// write code here
struct ListNode* cur;
struct ListNode* prev;
struct ListNode* next = NULL;
if(NULL == pHead)
{
//printf("input error\n");
return NULL;
}
cur = pHead;
prev = cur->next;
cur->next = next;
while(NULL != prev)
{
next = cur;
cur = prev;
prev = cur->next;
cur->next = next;
}
pHead = cur;
return pHead;
}
刚开始方案:
计算链表长度,遍历链表将数填到数组中,遍历链表将数组中数反序放到链表中。
有点麻烦而且报错。。。