LeetCode 206
Reverse Linked List
Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively.
Could you implement both?
1 /************************************************************************* 2 > File Name: LeetCode206.c 3 > Author: Juntaran 4 > Mail: JuntaranMail@gmail.com 5 > Created Time: Wed 18 May 2016 21:15:51 PM CST 6 ************************************************************************/ 7 8 /************************************************************************* 9 10 Reverse Linked List 11 12 Reverse a singly linked list. 13 14 Hint: 15 A linked list can be reversed either iteratively or recursively. 16 Could you implement both? 17 18 ************************************************************************/ 19 20 #include "stdio.h" 21 22 /** 23 * Definition for singly-linked list. 24 * struct ListNode { 25 * int val; 26 * struct ListNode *next; 27 * }; 28 */ 29 struct ListNode* reverseList(struct ListNode* head) 30 { 31 if( head==NULL || head->next==NULL ) 32 { 33 return head; 34 } 35 struct ListNode* temp = NULL; 36 struct ListNode* newhead = NULL; 37 38 while( head != NULL ) 39 { 40 temp = head->next; 41 head->next = newhead; 42 newhead = head; 43 head = temp; 44 } 45 46 return newhead; 47 }