办法一:设置三个指
C语言单链表逆置实现办法
办法一:设置三个指针进行其逆置
truct ListNode* ReverseList(struct ListNode* pHead ) {
struct ListNode *pre = pHead; // 需要要用struct ListNode *
if(pre ==NULL || pre -> next == NULL) //如头指针为空或只有头指针
return pHead;
struct ListNode *cur = pre->next;
struct ListNode *next = NULL; // 保存指针所指的地址,可理解为 cur = cur ->next
while( cur != NULL)
{
next = cur -> next; // 保存指针所指的地址,可理解为 cur = cur ->next
cur ->next = pre; // 第一个循环 第二节点 指向第一个节点
pre=cur; // 后移一位
cur=next; // cur 后移一位
}
pHead -> next = NULL; //如果少了此步,将运行错误
pHead = pre; // 先为循环的最后一步pre的地址为指针cur所指
return pHead;
}
其最终结果完成逆置(包括头节点)
办法二: 头插法
struct ListNode* ReverseList(struct ListNode* pHead ) {
// write code here
if(pHead ==NULL || pHead -> next == NULL) //如头指针为空或只有头指针
return pHead;
struct ListNode *p = pHead->next; // 需要要用struct ListNode *
struct ListNode *q;
pHead -> next = NULL;
while( p)
{
q = p;
p = p -> next;
q -> next = pHead -> next;
pHead -> next = q;
}
return pHead;