206。Reverse Linked List

Bertha 。 2022-06-10 14:43 343阅读 0赞

/*
Reverse a singly linked list.
*/
//解法一 21% 3ms
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
//思路:先创建iintnt 一个数组,查找一共有多少元素,然后放进数组中,利用数组倒转,然后再重新放到单链表中
struct ListNode* reverseList(struct ListNode* head) {
struct ListNode* p,*q;
int i=0,j,temp,count=0;
int* nums;
p = head;
while(p)
{
p = p->next;
count++;
}

  1. nums = (int\*)malloc(count\*sizeof(int\*));
  2. p = head;
  3. while(p)
  4. \{
  5. nums\[i\] = p->val;
  6. p = p->next;
  7. i++;
  8. \}
  9. for(i=0,j=count-1;i<count/2;i++,j--)
  10. \{
  11. temp = nums\[i\];
  12. nums\[i\] = nums\[j\];
  13. nums\[j\] = temp;
  14. \}
  15. p = head;
  16. i = 0;
  17. while(p)
  18. \{
  19. p->val = nums\[i\];
  20. p = p->next;
  21. i++;
  22. \}
  23. return head;

}

发表评论

表情:
评论列表 (有 0 条评论,343人围观)

还没有评论,来说两句吧...

相关阅读