给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。



就是不断头插,用头插法!
- /**
- * Definition for singly-linked list.
- * struct ListNode {
- * int val;
- * struct ListNode *next;
- * };
- */
-
-
- struct ListNode* reverseList(struct ListNode* head){
- struct ListNode* newhead = NULL;
- struct ListNode* cur = head;
- struct ListNode* next = NULL;
- while(cur)
- {
- next = cur->next;
- cur->next = newhead;
- newhead = cur;
- cur = next;
- }
- return newhead;
- }
改一下指针方向
- /**
- * Definition for singly-linked list.
- * struct ListNode {
- * int val;
- * struct ListNode *next;
- * };
- */
-
-
- struct ListNode* reverseList(struct ListNode* head){
- if(head == NULL)
- {
- return NULL;
- }
- struct ListNode* n1,*n2, *n3;
- n1 = NULL;
- n2 = head;
- n3 = n2->next;
- while(n2)
- {
- n2->next = n1;
- n1 = n2;
- n2 = n3;
- if(n3)
- n3 = n3->next;
- }
- return n1;
- }