牛客网-刷题-BM1 反转链表
#include <stdio.h> struct ListNode { int val; struct ListNode *next; }; struct ListNode* ReverseList(struct ListNode* pHead ) { if (pHead == NULL) return NULL; struct ListNode* end = pHead; struct ListNode* p = end->next; // 把p放在最前面,实现倒序 // 1.end的next指向p的next // 2.把head放到p之后 while(p != NULL) { end->next = p->next; p->next = pHead; pHead = p; p = end->next; } return pHead; } void printListNode(struct ListNode* pHead) { struct ListNode *p = pHead; while(p != NULL) { printf("%d ", p->val); p = p->next; } printf("\n"); } int main() { ListNode pHead; pHead.val = 1; ListNode node2; node2.val = 2; ListNode node3; node3.val = 3; node3.next = NULL; pHead.next = &node2; node2.next = &node3; printListNode(&pHead); struct ListNode*head = ReverseList(&pHead); printListNode(head); return 0; }