实例要求:
- 1、给定单链表的
头节点 head
; - 2、请反转链表;
- 3、最后返回反转后的链表;
案例展示:
实例分析:
- 1、入参合理性检查,即
head != NULL || head->next != NULL
; - 2、while循环遍历单链表;
- 3、将第二个数据节点依次头插到第一个数据节点前即可;
示例代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head) {
if(head == NULL || head->next == NULL){
return head;
}
struct ListNode *p = head;
struct ListNode *q = p->next;
p->next = NULL;
while(p){
p = q->next;
q->next = head;
head = q;
q = p;
}
return head;
}
运行结果: