Rotate List
来源:互联网 发布:玻璃优化软件破解版 编辑:程序博客网 时间:2024/06/05 06:50
自己搞定的,刚开始题目还没弄清
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given 1->2->3->4->5->NULL
and k = 2
,
return 4->5->1->2->3->NULL
.
分析: (关键在于k可能会很大)
1. list 是空的吗?
2. 连成一个圈,再k 取余, 再转
# Definition for singly-linked list.# class ListNode:# def __init__(self, x):# self.val = x# self.next = Noneclass Solution: # @param head, a ListNode # @param k, an integer # @return a ListNode def rotateRight(self, head, k): if head==None: return head cur = head count = 1 while cur.next!=None: cur = cur.next count += 1 cur.next = head k = k % count cur = head for dummy_i in range(count-k-1): cur = cur.next newhead = cur.next cur.next = None return newhead
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode *rotateRight(ListNode *head, int k) { if (head==NULL){ return head; } ListNode *cur = head; int count = 1; while (cur->next!=NULL){ cur = cur->next; count += 1; } cur->next = head; k = k % count; cur = head; for(i=1;i<=(count-k-1);i++){ cur = cur->next; } ListNode *newhead = cur->next; cur->next = NULL; return newhead; }};
0 0
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- rotate-list
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- UIView换UIImage
- 链表
- GetWindowRect和GetClientRect的区别详解
- Oracle GoldenGate Install For Linux
- LeetCode之旅(1)
- Rotate List
- 行内元素与块级元素比较全面的区别和转换
- Convert Sorted Array to Binary Search Tree
- Mongo使用
- 《javascript设计模式》读书笔记二(封装和隐藏信息)
- 互换两个变量,不使用中间变量
- 2015届毕业生的找工作记录
- 杨辉三角
- Android:自定义Button